当读取带有错误的 HttpResponse 时,下面的方法会失败:“内容已被消耗”。我知道内容只能被使用一次,但我在第一次尝试时就收到了这个错误,而且我没有在代码中看到我可能会使用它两次的任何地方。
private static String getData(String url, HttpParams params) {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
if (params != null) {
httpGet.setParams(params);
}
String result = "";
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
content.close();
result = builder.toString();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}