我想从this URL获取JSON,但由于JSON很大,服务器会慢慢加载JSON。 我通过以下代码从网上获取JSON:
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
if (params != null)
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
Log.i("TAG", sb.toString());
is.close();
json = sb.toString();
} catch (Exception e) {
Log.i("TAG", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.i("TAG", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
但我可以把第一部分作为JSON,我的JSON仍然不完整 请帮帮我。
答案 0 :(得分:0)
试试这种方式。
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
if (params != null)
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
json = getResponseBody(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.i("TAG", "Error parsing data " + e.toString());
}
return jObj;
}
添加此方法
public String getResponseBody(final HttpEntity entity) throws IOException, ParseException {
if (entity == null) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
InputStream instream = entity.getContent();
if (instream == null) {
return "";
}
if (entity.getContentLength() > Integer.MAX_VALUE) {
throw new IllegalArgumentException(
"HTTP entity too large to be buffered in memory");
}
StringBuilder buffer = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream, HTTP.UTF_8));
String line = null;
try {
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
} finally {
instream.close();
reader.close();
}
return buffer.toString();
}