简体   繁体   中英

How can I retrieve a feed in JSON from a Java Servlet?

I want to make an Http request and store the result in a JSONObject. I haven't worked much with servlets, so I am unsure as to whether I am 1) Making the request properly, and 2) supposed to create the JSONObject. I have imported the JSONObject and JSONArray classes, but I don't know where I ought to use them. Here's what I have:

     public void doGet(HttpServletRequest req, HttpServletResponse resp)
 throws IOException {

        //create URL    
        try {
            // With a single string.
            URL url = new URL(FEED_URL);

            // Read all the text returned by the server
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            String str;
            while ((str = in.readLine()) != null) {
                // str is one line of text; readLine() strips the newline character(s)
            }
            in.close();
        } catch (MalformedURLException e) {
        }
        catch (IOException e) {
        }

My FEED_URL is already written so that it will return a feed formatted for JSON.

This has been getting to me for hours. Thank you very much, you guys are an invaluable resource!

First gather the response into a String:

BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuilder fullResponse = new StringBuilder();
String str;
while ((str = in.readLine()) != null) {
  fullResponse.append(str);
}

Then, if the string starts with "{", you can use:

JSONObject obj = new JSONObject(fullResponse.toString()); //[1]

and if it starts with "[", you can use:

JSONArray arr = new JSONArray(fullResponse.toStrin()); //[2]

[1] http://json.org/javadoc/org/json/JSONObject.html#JSONObject%28java.lang.String%29

[2] http://json.org/javadoc/org/json/JSONArray.html#JSONArray%28java.lang.String%29

Firstly, this is actually not a servlet problem. You don't have any problems with javax.servlet API. You just have problems with java.net API and the JSON API.

For parsing and formatting JSON strings, I would recommend to use Gson (Google JSON) instead of the legacy JSON API's. It has much better support for generics and nested properties and can convert a JSON string to a fullworthy javabean in a single call.

I've posted a complete code example before here . Hope you find it useful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM