Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I display a Java HttpPost object as a string?

I am creating an HttpPost object in Android to communicate with a server operated by a client. Unfortunately the server isn't providing either of us with very useful error messages; I would like to see the content of the HttpPost object as a string so I can send it to our client and he can compare it with what he's expecting.

How can I convert an HttpPost object into a string that reflects how it would look as it arrived at the server?

like image 511
Andrew Wyld Avatar asked Sep 06 '12 16:09

Andrew Wyld


1 Answers

Should use it after execute

public static String httpPostToString(HttpPost httppost) {
    StringBuilder sb = new StringBuilder();
    sb.append("\nRequestLine:");
    sb.append(httppost.getRequestLine().toString());

    int i = 0;
    for(Header header : httppost.getAllHeaders()){
      if(i == 0){
          sb.append("\nHeader:");
      }
        i++;
        for(HeaderElement element : header.getElements()){
            for(NameValuePair nvp :element.getParameters()){
                sb.append(nvp.getName());
                sb.append("=");
                sb.append(nvp.getValue());
                sb.append(";");
            }
        }
    }
    HttpEntity entity = httppost.getEntity();

    String content = "";
    if(entity != null){
        try {

            content = IOUtils.toString(entity.getContent());
        } catch (Exception e) {
            e.printStackTrace();
        } 
    }
    sb.append("\nContent:");
    sb.append(content);


    return sb.toString();
}

snippet

like image 141
Sven Jörns Avatar answered Nov 15 '22 00:11

Sven Jörns