我想从 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 对象。