使用HttpClient写入正文请求

时间:2013-08-12 13:18:49

标签: java xml request apache-httpclient-4.x

我想用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编写正文......

2 个答案:

答案 0 :(得分:104)

如果您的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

编写

答案 1 :(得分:22)

扩展您的代码(假设您要发送的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);