63

我想用 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");

而且我不知道如何继续用我的 XML 编写正文...

4

2 回答 2

118

如果您的 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());
    }

注意异常。

BTW,例子是httpclient 4.x版本写的

于 2013-08-12T13:35:14.377 回答
26

扩展您的代码(假设您要发送的 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);
于 2013-08-12T13:38:06.940 回答