我想创建一个Http请求并将结果存储在JSONObject中。我没有使用servlet,所以我不确定我是否1)正确地发出请求,2)应该创建JSONObject。我已经导入了JSONObject和JSONArray类,但我不知道应该在哪里使用它们。这就是我所拥有的:
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) {
}
我的FEED_URL已经写好,因此会返回格式化为JSON的Feed。
这已经让我好几个小时。非常感谢,你们是宝贵的资源!
答案 0 :(得分:2)
首先将响应收集到一个字符串中:
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuilder fullResponse = new StringBuilder();
String str;
while ((str = in.readLine()) != null) {
fullResponse.append(str);
}
然后,如果字符串以“{”开头,则可以使用:
JSONObject obj = new JSONObject(fullResponse.toString()); //[1]
如果以“[”开头,则可以使用:
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
答案 1 :(得分:0)