在我的项目中,我使用 HttpClient 调用 URL 并获得带有 15-20 Base64 字符串的 JSON 响应。HttpClient 代码如下。
public static JSONObject TestHttpPost(String url,
List<NameValuePair> nameValuePairs) {
long t = System.currentTimeMillis();
HttpClient client = new DefaultHttpClient();
Log.i(TAG, "HTTPResponse received in ["
+ (System.currentTimeMillis() - t) + "ms]");
HttpPost post = new HttpPost(url);
try {
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String resultString = convertStreamToString(rd);
JSONObject jsonObjRecv = new JSONObject(resultString);
Log.i(TAG, "<JSONObject>\n" + jsonObjRecv.toString()
+ "\n</JSONObject>");
return jsonObjRecv;
} catch (Exception e) {
return null;
}
}
private static String convertStreamToString(BufferedReader reader) {
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
我面临以下问题
- 当我使用 convertStreamToString() 处理响应时,我无法获得整个响应。
2 由于 Base64 字符串太大,StringBuilder 无法存储整个图像字符串。该函数只返回 JSON 的一小部分。而且要花太多时间来处理。