我如何才能从我的HTTP响应的android一个字符串?我的、字符串、HTTP、android

2023-09-06 02:29:17 作者:月亮惹的祸

我见过的人写了自己的转换的Htt的presponse为一个字符串以后使用的方法还真有些难看code,这看起来是这样的:

I've seen some really ugly looking code from people writing up their own methods of converting an HttpResponse to a string to use later, that looks something like this:

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();

不仅是有点乱,但它确实难看,我很多时候分不清什么是与code,因为这个烂摊子precedes这回事。有没有更好的方式来做到这一点?

not only is that somewhat of a mess, but it's really ugly and I often times can't tell what's going on with the code because this mess precedes it. Is there any better way to do this?

推荐答案

是的,有!你可以做所有的,在一号线!像这样:

YES, THERE IS! YOU CAN DO ALL OF THAT IN ONE LINE! Just like this:

response = client.execute(post);
String responseStr = EntityUtils.toString(response.getEntity());

开心应用使得

happy app making