Write in body request with HttpClient

Tata2 picture Tata2 · Aug 12, 2013 · Viewed 129.3k times · Source

I want to write the body of a request with XML content-type but I don't know how with HttpClient Object ( http://hc.apache.org/httpclient-3.x/apidocs/index.html )

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpRequest = new HttpPost(this.url);
httpRequest.setHeader("Content-Type", "application/xml");

And I don't know how to continue to write the body with my XML ...

Answer

Larry.Z picture Larry.Z · Aug 12, 2013

If your xml is written by java.lang.String you can just using HttpClient in this way

    public void post() throws Exception{
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://www.baidu.com");
        String xml = "<xml>xxxx</xml>";
        HttpEntity entity = new ByteArrayEntity(xml.getBytes("UTF-8"));
        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        String result = EntityUtils.toString(response.getEntity());
    }

pay attention to the Exceptions.

BTW, the example is written by the httpclient version 4.x