[英]How can I retrieve a feed in JSON from a Java Servlet?
我想發出一個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的供稿。
這已經給我幾個小時了。 非常感謝您,你們是寶貴的資源!
首先將響應收集到一個字符串中:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.