6

I'm now trying to get JSON Object with using HTTP request in Java cord.

I want to know how I can get response or JSON object in the following cord.

Please let me know.

(In this program, I try to get Wikipedia categories of the article "New York". )

 String requestURL = "http://en.wikipedia.org/w/api.php?action=query&prop=categories&format=json&clshow=!hidden&cllimit=10&titles=" + words[i];
 URL wikiRequest = new URL(requestURL);
 URLConnection connection = wikiRequest.openConnection();  
 connection.setDoOutput(true);  

                    /**** I'd like to get response here. ****/

 JSONObject json = Util.parseJson(response);
1
  • Do NOT do this. You will get OOM's if the request is relatively big and it will be very hard to fix. Commented May 19, 2013 at 22:46

4 Answers 4

4

Just 2 lines of code with JSONTokener

JSONTokener tokener = new JSONTokener(wikiRequest.openStream());
JSONObject root = new JSONObject(tokener);
Sign up to request clarification or add additional context in comments.

1 Comment

URL.openStream() returns an InputStream... JSONTokener expects an String though?
3
Scanner scanner = new Scanner(wikiRequest.openStream());
String response = scanner.useDelimiter("\\Z").next();
JSONObject json = Util.parseJson(response);
scanner.close();

2 Comments

What library contains the Util class you are using? This answer might force the developer to include a new dependency that they might not want.
It was in the original question. I do not know what is behind. I reused it in my answer because if this method does what its name suggests then there is no reason to change it to something else (at least in the scope of this question).
0

If you are using URLConnection you should be able to read the stream instead of getting a response object:

BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

see: http://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html

Comments

0

Sample implementation with corn-httpclient & corn-converter

HttpClient client = new HttpClient(new URI(http://en.wikipedia.org/w/api.php?action=query&prop=categories&format=json&clshow=!hidden&cllimit=10&titles=" + words[i]));
HttpResponse response = client.sendData(HTTP_METHOD.GET);
if (! response.hasError()) {
String jsonString = response.getData();
JsTypeComplex jsonResponse =  (JsTypeComplex) JsonStringParser.parseJsonString(jsonString);
JsTypeList resultsArr = (JsTypeList) jsonResponse.get("results");

Maven dependencies:

<dependency>
    <groupId>net.sf.corn</groupId>
    <artifactId>corn-httpclient</artifactId>
    <version>1.0.0</version>
</dependency>
<dependency>
    <groupId>net.sf.corn</groupId>
    <artifactId>corn-converter</artifactId>
    <version>1.0.0</version>
</dependency>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.