【问题标题】:Apache HTTP Client 400 ErrorApache HTTP 客户端 400 错误
【发布时间】:2018-06-24 14:42:06
【问题描述】:

我正在尝试自动化 Web 服务,我以字符串的形式传递 XML,然后将其转换为字符串实体并设置实体。但我不知道它为什么会抛出 400 错误。我是 WebServices Automation 的新手,请帮助我。

以下是我的代码:

package com.WebServices.Automation;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.junit.Assert;
import org.junit.Test;

public class HTTPClientA {

    static String url = "http://www.dneonline.com/calculator.asmx?wsdl";

    String xml = "\"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+
            "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:tem=\"http://tempuri.org/\">\r\n" + 
            "   <soap:Header/>\r\n" + 
            "   <soap:Body>\r\n" + 
            "      <tem:Add>\r\n" + 
            "         <tem:intA>10</tem:intA>\r\n" + 
            "         <tem:intB>20</tem:intB>\r\n" + 
            "      </tem:Add>\r\n" + 
            "   </soap:Body>\r\n" + 
            "</soap:Envelope>";
    @Test
    public void main() throws ClientProtocolException, IOException
    {

        StringEntity stringEntity = new StringEntity(xml);
        HttpPost post = new HttpPost(url);
        post.setEntity(stringEntity);
        HttpClient client = HttpClientBuilder.create().build();
        post.setHeader("Content-Type", "text/xml; charset=utf-8");
        post.setHeader("SOAPAction", "http://tempuri.org/Add");
        HttpResponse res = client.execute(post);

        int actualresponse = res.getStatusLine().getStatusCode();
        System.out.println(actualresponse);
        try
        {
        Assert.assertEquals(actualresponse, 200);
        }
        catch (Exception e) {
            // TODO: handle exception
        } 
        HttpEntity entity = res.getEntity();

            String strResponse = null;
            if (entity != null) {
                strResponse = EntityUtils.toString(entity);
                System.out.println(strResponse);
            }
    }

}

【问题讨论】:

  • 试试String xml = "&lt;?xml version ...
  • 谢谢@user7294900,您的回答帮助我解决了我的问题。

标签: java httpclient apache-httpclient-4.x webservice-client


【解决方案1】:

您的 XML 无效,它以双引号而不是 &lt;?xml 开头,请将您的分配改为:

  String xml = "<?xml version ... –

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-04
    • 1970-01-01
    • 1970-01-01
    • 2014-12-12
    相关资源
    最近更新 更多