67

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 ...

Tata2
  • 893
  • 2
  • 8
  • 14

2 Answers2

121

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

Larry.Z
  • 3,694
  • 1
  • 20
  • 17
  • 1
    I would suggest using `java.nio.charset.StandardCharsets`, and modify the `ByteArrayEntity` line into: HttpEntity entity = new ByteArrayEntity(xml.getBytes(StandardCharsets.UTF_8)); – MrMister Aug 29 '16 at 11:23
  • 3
    Instead of `new ByteArrayEntity(xml.getBytes("UTF-8"));` use `new StringEntity(xml, ContentType.APPLICATION_XML);` – Asaph Oct 26 '16 at 22:56
  • Using new StringEntity may result in the incorrect charset declared in the header. Use with care. – Jeremy Brooks Apr 20 '17 at 20:32
  • 3
    Should use [HttpClientBuilder.create().build()](https://stackoverflow.com/a/32372938) instead since `DefaultHttpClient` is deprecated. – neuront Feb 05 '18 at 04:48
  • I am hitting an endpoint that is created by me only on another Spring boot application and it is a post method but it is giving error as request body not found. I implemented the answer. I don't know what else to do. – Drishti Jain Nov 24 '22 at 09:18
28

Extending your code (assuming that the XML you want to send is in xmlString) :

String xmlString = "</xml>";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpRequest = new HttpPost(this.url);
httpRequest.setHeader("Content-Type", "application/xml");
StringEntity xmlEntity = new StringEntity(xmlString);
httpRequest.setEntity(xmlEntity );
HttpResponse httpresponse = httpclient.execute(httppost);
Santosh
  • 17,667
  • 4
  • 54
  • 79