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

后端 未结 2 2322
旧时难觅i
旧时难觅i 2021-02-19 23:11

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:

相关标签:
2条回答
  • 2021-02-19 23:21

    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

    0 讨论(0)
  • 2021-02-19 23:34

    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.

    0 讨论(0)
提交回复
热议问题