如何从我的http响应android获取一个字符串?

Aus*_*tin 12 string android http httpresponse

我已经看到一些非常难看的代码来自人们编写自己的方法将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();
Run Code Online (Sandbox Code Playgroud)

这不仅是一个混乱,但它真的很难看,而且我常常无法分辨代码发生了什么,因为这个混乱在它之前.有没有更好的方法来做到这一点?

Aus*_*tin 43

就在这里!你可以在一条线上完成所有这些!像这样:

response = client.execute(post);
String responseStr = EntityUtils.toString(response.getEntity());
Run Code Online (Sandbox Code Playgroud)

快乐的应用程序