使用HttpClient写入正文请求
问题描述:
我想用XML内容类型编写请求的主体,但我不知道如何使用HttpClient对象(http://hc.apache.org/httpclient-3.x/apidocs/index.html )
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");
我不知道如何继续使用我的XML编写正文...
And I don't know how to continue to write the body with my XML ...
答
如果您的xml是由 java.lang.String
编写的,那么你可以以这种方式使用 HttpClient
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());
}
注意例外情况。
BTW,示例由httpclient版本4.x
BTW, the example is written by the httpclient version 4.x