Apache HTTP客户端400错误

时间:2018-06-24 14:42:06

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

我试图使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);
            }
    }

}

1 个答案:

答案 0 :(得分:1)

您的XML无效,它以双引号而不是languages开头,将您的分配更改为以以下开头:

<?xml