我已经看到一些非常难看的代码,人们编写了自己的将 HttpResponse 转换为字符串以供以后使用的方法,看起来像这样:
httppost.setEntity(new UrlEncodedFormEntity(valuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF8"),8);
StringBuilder sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
String result = sb.toString();
这不仅有点乱,而且真的很丑陋,而且我经常无法分辨代码发生了什么,因为这种混乱在它之前。有没有更好的方法来做到这一点?