使用HttpClient写入正文请求

Tat*_*ta2 56 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");
Run Code Online (Sandbox Code Playgroud)

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

Lar*_*y.Z 109

如果您的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());
    }
Run Code Online (Sandbox Code Playgroud)

注意例外情况.

顺便说一下,这个例子是由httpclient版本4.x编写的

  • 代替 `new ByteArrayEntity(xml.getBytes("UTF-8"));` 使用 `new StringEntity(xml, ContentType.APPLICATION_XML);` (2认同)
  • 应该使用 [HttpClientBuilder.create().build()](/sf/answers/2266105691/) 代替,因为不推荐使用 `DefaultHttpClient`。 (2认同)

San*_*osh 24

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