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

三世轮回 提交于 2019-12-09 14:51:42

问题


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?


回答1:


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




回答2:


I did it with response handler from the HttpClient.execute documentation. Using handler as a second parameter to the .execute method defines in what format the response should be.
My code is as folows:

HttpClient client = new DefaultHttpClient();

        HttpGet request = new HttpGet(params[0]);
        ResponseHandler<String> handler = new BasicResponseHandler();
        String response = "";
        try {
            response = client.execute(request, handler);
        } catch (IOException e) {
            e.printStackTrace();
        }

params[0] is a URL in form of a string. It may be important to say that my server returns responses in JSON. So in the end I convert my response string to JSON.



来源:https://stackoverflow.com/questions/15618792/how-do-i-get-a-string-from-my-http-response-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!