HTTPResponse as JSON in Java

≡放荡痞女 提交于 2019-12-08 19:39:39

问题


I was trying to get an JSONObject from a HTTP response.

try
    {   
        GetMethod postMethod = new GetMethod();
        postMethod.setURI(new URI(url, true));
        postMethod.setRequestHeader("Accept", "application/json");
        httpClient.executeMethod(postMethod);
        String resp=postMethod.getResponseBodyAsString();
        org.json.JSONTokener tokener = new org.json.JSONTokener(resp);
        finalResult = new org.json.JSONArray(tokener);

        return finalResult;
    }

But I got a runtime warning as

Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.

Should I get the response as stream as suggested by the JVM ? If so, how could I parse the JSON from it ?


回答1:


if you want to send jsonObjects from server suppose (tomcat server)

For server side-

creating jsonobjects-

I have Called toJson() for creating jsonobjects this is the implementation-

final JSONObject arr = new JSONObject();

for (int i = 0; i < contactStatus.size(); i++) {
    ContactStatus contactObject = contactStatus.get(i);

    try {
        arr.put(String.valueOf(i), toJson(value1, value2,, value3));
    } catch (JSONException e) {

     catch block e.printStackTrace();
    }
}

//Here we serialize the stream to a String.
final String output = arr.toString();
response.setContentLength(output.length());
out.print(output);//out is object of servlet output stream.

public static Object toJsonForContact(String value1, boolean value2, double value3) throws JSONException {

    JSONObject contactObject = new JSONObject();
    contactObject.put("id", id);
    contactObject.put("status", value1);
    contactObject.put("distance", value2);
    contactObject.put("relation", value3);
    return contactObject;
}

so your jsonobjects are ready for sending we write these objects to ServletoutputStream.

in client side-

while ((ReadResponses = in.readLine()) != null) {
        Constants.Response_From_server = ReadResponses;

        if (Constants.Response_From_server.startsWith("{")) {
            ListOfContactStatus = new ArrayList<ContactStatus>();
            ContactStatus contactStatusObject;

            try {
                JSONObject json = new JSONObject(Constants.Response_From_server);

                for (int i = 0; i < json.length(); i++) {
                    contactStatusObject = new ContactStatus();

                    JSONObject json1 = json.getJSONObject(String.valueOf(i));
                    System.out.println("" + json1.getString("id"));
                    System.out.println("" + json1.getBoolean("status"));
                    System.out.println("" + json1.getDouble("distance"));

                    contactStatusObject.setId(json1.getString("id"));
                    contactStatusObject.setStatus(json1.getBoolean("status"));
                    contactStatusObject.setDistance((float) json1.getDouble("distance"));
                    ListOfContactStatus.add(contactStatusObject);
                    System.out.println("HTTPTransport:sendMessage  Size of ListOfContactStatus" + ListOfContactStatus.size());
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}



回答2:


Has your server been set up to inform clients how big its responses are? If not, your server is streaming the data, and it's technically impossible to tell how much buffer space is required to deal with the response, warranting a warning that something potentially dangerous is going on.




回答3:


You can easily generate JSonObject usin Java EE 7. The sample code.

    JsonReader reader = Json.createReader(new URI(url, true));
    JsonObject jsonObject=reader.readObject();

For details information go through to the link. http://docs.oracle.com/javaee/7/tutorial/doc/jsonp003.htm#BABHAHIA



来源:https://stackoverflow.com/questions/17191412/httpresponse-as-json-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!