使用 HttpClient 写入正文请求

2022-08-31 15:17:45

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


答案 1

如果你的xml是由你编写的,你可以用这种方式java.lang.StringHttpClient

    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());
    }

注意例外情况。

顺便说一句,该示例由 httpclient 版本 4.x 编写


答案 2

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

推荐