Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I get a string from my http response android?

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

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?

like image 784
Austin Avatar asked Mar 25 '13 15:03

Austin


1 Answers

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

like image 82
Austin Avatar answered Oct 21 '22 05:10

Austin