作者:低碳的S | 来源:互联网 | 2023-05-18 02:08
后台返回的json字符串较大(100K左右),用HttpURLConnection或HttpClient都没法获得完整的数据,都是获得40K左右,后面就没了,不知道大伙遇到过这类问题吗?代码如下1
后台返回的json字符串较大(100K左右),用HttpURLConnection或HttpClient都没法获得完整的数据,都是获得40K左右,后面就没了,不知道大伙遇到过这类问题吗?代码如下
1、这是使用HttpClient 的
try {
HttpGet httpRequest = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(httpRequest);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
InputStream input = httpResponse.getEntity().getContent();
byte[] b = new byte[1024];
int len = 0;
StringBuffer buff = new StringBuffer();
while ((len = input.read(b)) != -1) {
buff.append(new String(b));
}
return buff.toString();
// 使用如下代码只返回40K
// return EntityUtils.toString(httpResponse.getEntity(),"UTF-8");
}
} catch ...
2、这是直接用HttpURLConnection的
try {
URL url = new URL(urlStr);
if (null != url) {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
if (null == urlConnection) {
return null;
}
urlConnection.setConnectTimeout(3000);
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
// /< 获得服务器的响应结果和状态码
int responseCode = urlConnection.getResponseCode();
if (200 == responseCode) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int len = 0;
String result = "";
if (null != urlConnection.getInputStream()) {
while ((len = urlConnection.getInputStream().read(data)) != -1) {
outputStream.write(data, 0, len);
}
result = new String(outputStream.toByteArray());
return result;
}
}
}
} catch ...
7 个解决方案
代码貌似没有问题,
字符串可以直接String msg = EntityUtils.toString(response.getEntity());
而流用URLConnection; conn.getInputStream();
用抓包工具看下发送的头和response ,另外logcat输出是有限制的,用adb shell里面logcat看看是否完整
注意到你用的HttpGet ,是不是前面有缓存,
可以对比下完整的字符串A和部分的字符串B,是不是B真的是A的前面一部分,
可能性:
1.缓存,实际取的前面的请求数据,
2.get请求的长度限制,换post,
http://blog.csdn.net/yijianpiaoxue2014/article/details/49094179可以看一下这篇文章,希望能解决你的问题