Problems with restfull api

3

I have a Restfull API on the local Apache server that returns a list of users from the database (localhost / api / users).

I'm using JSONLint to validate my JSON. When I access via browser I get the result and it is valid in JSONLint, which returns me as valid JSON. An example returned by the API:

{
    "usuarios": [
        {
            "id": 167,
            "contrato": 1,
            "cod": "1212",
            "nome": "Marcos Roberto Pavesi",
            "email": "[email protected]",
            "senha": "114fdfefd3d69799f0b6f73ef764d405",
            "ativo": "S",
            "setor": "1",
            "max_add": "",
            "dealer": 0
        },
        {
            "id": 520,
            "contrato": 1,
            "cod": "",
            "nome": "avaliador",
            "email": "[email protected]",
            "senha": "e10adc3949ba59abbe56e057f20f883e",
            "ativo": "S",
            "setor": "2",
            "max_add": "",
            "dealer": 0
        }
    ]
}

However, I'm trying to access my application via Java by following explanation and I'm getting the following error: / p>

  

Exception in thread "main" org.json.JSONException:
  A JSONObject text must begin with '{' at 1 [character 2 line 1]

  at org.json.JSONTokener.syntaxError (JSONTokener.java:433)
  at org.json.JSONObject. (JSONObject.java:197)
  at org.json.JSONObject. (JSONObject.java:324)
  at com.main.main.main (Main.java:14)

I'm accessing the api with the following code ...

public static void main(String[] args) {


        JSONObject obj = new JSONObject("http://localhost:8080/api_carmaix/api/usuarios");
        JSONArray arr = null;
        try {
                arr = obj.getJSONArray("usuarios");
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }




            for (int i = 0; i < arr.length(); i++)
            {            
                System.out.println(arr.getJSONObject(i).getString("id")); 

            }
}

}

    
asked by anonymous 02.10.2015 / 17:00

1 answer

1

Keep in mind that classes in this package do not make requests. They do the parse of some source (% with%,% with of%, ...) and allow you to manipulate the object as a JSON.

Your code throws a String because it's expected a string started by " Map " and you are passing a url.

You need to split things up: First make the request to get the response from your API - and here it does not have to be anything complex, you can get the answer as a string. Once you have the answer in hand, you create a JSONException and pass that string as an argument to the constructor.

You can create a method that looks up JSON in an url:

public String getJSON(String url){
    String data = null;

    try {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setRequestMethod("GET");
        connection.connect();

        if(connection.getResponseCode() == 200){
            try (BufferedReader buff = new BufferedReader(new InputStreamReader(connection.getInputStream()))){
                String line;
                StringBuilder builder = new StringBuilder();

                while((line = buff.readLine()) != null)
                    builder.append(line);
                data = builder.toString();
            }
        }
    } catch(Exception err){
        // Algum tratamento :)
    }
    return data;
}

Having this method, you can call it by passing the URL that your API returns JSON to the users. And the return, can pass in the constructor of { :

// Resposta da API
String data = getJSON("http://localhost:8080/api_carmaix/api/usuarios");

if (data != null) {
    try {
       // Usando a resposta da API para criar um objeto JSON:
       JSONObject json = new JSONObject(data);

       JSONArray jsonArray = json.getJSONArray("usuarios");
       for (int i = 0; i < jsonArray.length(); i++)
           System.out.println("ID: " + jsonArray.getJSONObject(i).getInt("id"));

    } catch (Exception err) {}
} 

Also note that while traversing JSONObject , I used JSONObject instead of JSONArray as you are using. If you try to get the value of "id" as a string a getInt will also be thrown containing the message:

  

JSONObject ["id"] not a string.

    
02.10.2015 / 20:13