Java 使用 HttpClient 写入正文请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18188041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Write in body request with HttpClient
提问by Tata2
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)
我想用 XML 内容类型编写请求的正文,但我不知道如何使用 HttpClient 对象(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 ...
而且我不知道如何继续用我的XML编写正文......
采纳答案by Larry.Z
If your xml is written by java.lang.String
you can just using HttpClient
in this way
如果你的xml是由java.lang.String
你写的,你可以HttpClient
这样使用
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
顺便说一句,该示例是由 httpclient 4.x 版编写的
回答by Santosh
Extending your code (assuming that the XML you want to send is in xmlString
) :
扩展您的代码(假设您要发送的 XML 在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);