在这里,我试图从URL获取Json数据。但是oit仅显示部分数据。以下是我如何读取数据的详细信息
BufferedInputStream是;
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("Accept", "application/json");
HttpResponse httpResponse = getHttpClient().execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = new BufferedInputStream(httpEntity.getContent()) ;
public void getJsonwithByteArray(BufferedInputStream istream) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int ctr;
try {
ctr = istream.read();
while (ctr != -1) {
byteArrayOutputStream.write(ctr);
ctr = istream.read();
}
istream.close();
} catch (IOException e) {
e.printStackTrace();
}
Log.v("Text Data", byteArrayOutputStream.toString());
try {
// Parse the data into jsonobject to get original data in form of
// json.
JSONObject jObject = new JSONObject(
byteArrayOutputStream.toString());
jObj = jObject;
Log.v("JsonParser", "JsonByteArry data: " + jObj.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
尝试使用此方法读取响应
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();
}
如何使用?
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("Accept", "application/json");
HttpResponse httpResponse = getHttpClient().execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
String response = getResponseBody(httpEntity);
try {
// Parse the data into jsonobject to get original data in form of
// json.
JSONObject jObject = new JSONObject(
response);
jObj = jObject;
Log.v("JsonParser", "JsonByteArry data: " + jObj.toString());
} catch (Exception e) {
e.printStackTrace();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句