【发布时间】:2013-08-07 02:03:58
【问题描述】:
我想从 Http 获取响应中获取 JSON 对象:
这是我当前的 Http get 代码:
protected String doInBackground(String... params) {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(params[0]);
HttpResponse response;
String result = null;
try {
response = client.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
result = convertStreamToString(instream);
// now you have the string representation of the HTML request
System.out.println("RESPONSE: " + result);
instream.close();
if (response.getStatusLine().getStatusCode() == 200) {
netState.setLogginDone(true);
}
}
// Headers
org.apache.http.Header[] headers = response.getAllHeaders();
for (int i = 0; i < headers.length; i++) {
System.out.println(headers[i]);
}
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return result;
}
这里是 convertSteamToString 函数:
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
现在我只是得到一个字符串对象。如何取回 JSON 对象。
【问题讨论】:
-
你在结果字符串中得到了什么?
-
你为什么要使用 response.getEntity() 两次?
-
要返回一个 JSON 对象,请不要连接到您连接的网络服务器以向您发送一个 JSON?它会这样做吗?
-
@Zapnologica 检查我的答案。另请参阅 agen451 答案