【问题标题】:Write in body request with HttpClient使用 HttpClient 写入正文请求
【发布时间】:2013-08-13 19:50:17
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      注意例外情况。

      顺便说一句,例子是httpclient 4.x版本写的

      【讨论】:

      • 我建议使用java.nio.charset.StandardCharsets,并将ByteArrayEntity这一行修改为:HttpEntity entity = new ByteArrayEntity(xml.getBytes(StandardCharsets.UTF_8));
      • new ByteArrayEntity(xml.getBytes("UTF-8"));代替new StringEntity(xml, ContentType.APPLICATION_XML);
      • 使用新的 StringEntity 可能会导致在标头中声明的字符集不正确。小心使用。
      • 应该使用HttpClientBuilder.create().build(),因为DefaultHttpClient已被弃用。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-06
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多