1

I have the following code for make a post to an url an retrieve the response as a String. But I'd like to get also the HTTP response code (404,503, etc). Where can I recover it? I've tried with the methods offered by the HttpReponse class but didn't find it.

Thanks

public static String post(String url, List<BasicNameValuePair> postvalues) {
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);

        if ((postvalues == null)) {
            postvalues = new ArrayList<BasicNameValuePair>();
        }
        httppost.setEntity(new UrlEncodedFormEntity(postvalues, "UTF-8"));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
        return requestToString(response);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

}


private static String requestToString(HttpResponse response) {
    String result = "";
    try {
        InputStream in = response.getEntity().getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder str = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            str.append(line + "\n");
        }
        in.close();
        result = str.toString();
    } catch (Exception ex) {
        result = "Error";
    }
    return result;
}
Addev
  • 31,819
  • 51
  • 183
  • 302

3 Answers3

5

You can modify your code like this:

//...
HttpResponse response = httpclient.execute(httppost);
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
  //edit: there is already function for this
  return EntityUtils.toString(response.getEntity(), "UTF-8");
} else {
  //Houston we have a problem
  //we should do something with bad http status
  return null;
}

EDIT: just one more thing ... instead of requestToString(..); you can use EntityUtils.toString(..);

Selvin
  • 6,598
  • 3
  • 37
  • 43
2

Have you tried the following?

response.getStatusLine().getStatusCode() 
Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
user1452132
  • 1,758
  • 11
  • 21
2

Have you tried this?

    // Execute HTTP Post Request
    HttpResponse response = httpclient.execute(httppost);
    response.getStatusLine().getStatusCode();
Stefan Buynov
  • 389
  • 1
  • 7