Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write in body request with HttpClient

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

like image 854
Tata2 Avatar asked Aug 12 '13 13:08

Tata2


People also ask

How do I send a body in HttpClient request?

you can't send a body with a GET request, not with HttpClient or WebClient or anything else. but even if you manage to do it at low level, the server won't parse the body anyways because it will treat it as a GET request.


2 Answers

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

like image 103
Larry.Z Avatar answered Sep 20 '22 22:09

Larry.Z


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); 
like image 27
Santosh Avatar answered Sep 18 '22 22:09

Santosh