Httpclient远程调用WebService示例(Eclipse+httpclient

感谢大神,仅作备忘(http://www.cnblogs.com/lanxuezaipiao/archive/2013/05/10/3072216.html)


 我们将Web Service发布在Tomcat或者其他应用服务器上后,有很多方法可以调用该Web Service,常用的有两种:

      1、通过浏览器HTTP调用,返回规范的XML文件内容
      2、通过客户端程序调用,返回结果可自定义格式


      接下来,我利用Eclipse作为开发工具,演示一个Httpclient调用WebService的简单示例
      

      第一步:新建Java Project,项目名称为HttpCallWebService

      第二步:将所需jar包导入到库中

      第三步:编写调用class,这里有两种方式调用,即GET方式和POST方式,由于POST方式较安全,故这里采用POST方式调用;请求数据的构造也有两种方式:静态和动态构造,下面分别介绍这两种方式:

      注:这里以E邮宝开放的webservice接口为例调用其中一个API函数,而E邮宝的webservice基于SOAP,故请求数据为SOAP格式,大家可根据自己情况进行修改

      静态构造请求数据:

package com.http;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;

public class StaticHttpclientCall {

    /**
     * @param args
     * @throws IOException
     * @throws HttpException
     */
    public static void main(String[] args) throws HttpException, IOException {
        // TODO Auto-generated method stub

        String soapRequestData = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
                + "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
                + " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""
                + " xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">"
                + " <soap12:Body>"
                + " <GetAPACShippingPackage xmlns=\"http://shippingapi.ebay.cn/\">"
                + " <GetAPACShippingPackageRequest>"
                + " <TrackCode>123</TrackCode>"
                + " <Version>123</Version>"
                + " <APIDevUserID>123</APIDevUserID>"
                + " <APIPassword>123</APIPassword>"
                + " <APISellerUserID>123</APISellerUserID>"
                + " <MessageID>123</MessageID>"
                + " </GetAPACShippingPackageRequest>"
                + " </GetAPACShippingPackage>" + "</soap12:Body>"
                + " </soap12:Envelope>";

        System.out.println(soapRequestData);

        PostMethod postMethod = new PostMethod(
                "http://epacketws.pushauction.net/v3/orderservice.asmx?wsdl");

        // 然后把Soap请求数据添加到PostMethod中
        byte[] b = soapRequestData.getBytes("utf-8");
        InputStream is = new ByteArrayInputStream(b, 0, b.length);
        RequestEntity re = new InputStreamRequestEntity(is, b.length,
                "application/soap+xml; charset=utf-8");
        postMethod.setRequestEntity(re);

        // 最后生成一个HttpClient对象,并发出postMethod请求
        HttpClient httpClient = new HttpClient();
        int statusCode = httpClient.executeMethod(postMethod);
        if(statusCode == 200) {
            System.out.println("调用成功!");
            String soapResponseData = postMethod.getResponseBodyAsString();
            System.out.println(soapResponseData);
        }
        else {
            System.out.println("调用失败!错误码:" + statusCode);
        }

    }

}


    动态构造数据:

package com.http;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;

// 动态构造调用串,灵活性更大
public class DynamicHttpclientCall {

    private String namespace;
    private String methodName;
    private String wsdlLocation;
    private String soapResponseData;

    public DynamicHttpclientCall(String namespace, String methodName,
            String wsdlLocation) {

        this.namespace = namespace;
        this.methodName = methodName;
        this.wsdlLocation = wsdlLocation;
    }

    private int invoke(Map<String, String> patameterMap) throws Exception {
        PostMethod postMethod = new PostMethod(wsdlLocation);
        String soapRequestData = buildRequestData(patameterMap);

        byte[] bytes = soapRequestData.getBytes("utf-8");
        InputStream inputStream = new ByteArrayInputStream(bytes, 0,
                bytes.length);
        RequestEntity requestEntity = new InputStreamRequestEntity(inputStream,
                bytes.length, "application/soap+xml; charset=utf-8");
        postMethod.setRequestEntity(requestEntity);

        HttpClient httpClient = new HttpClient();
        int statusCode = httpClient.executeMethod(postMethod);
        soapResponseData = postMethod.getResponseBodyAsString();

        return statusCode;
    }

    private String buildRequestData(Map<String, String> patameterMap) {
        StringBuffer soapRequestData = new StringBuffer();
        soapRequestData.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
        soapRequestData
                .append("<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
                        + " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""
                        + " xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">");
        soapRequestData.append("<soap12:Body>");
        soapRequestData.append("<" + methodName + " xmlns=\"" + namespace
                + "\">");
        soapRequestData.append("<" + methodName + "Request>");

        Set<String> nameSet = patameterMap.keySet();
        for (String name : nameSet) {
            soapRequestData.append("<" + name + ">" + patameterMap.get(name)
                    + "</" + name + ">");
        }
        
        soapRequestData.append("</" + methodName + "Request>");
        soapRequestData.append("</" + methodName + ">");
        soapRequestData.append("</soap12:Body>");
        soapRequestData.append("</soap12:Envelope>");

        return soapRequestData.toString();
    }

    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub

        DynamicHttpclientCall dynamicHttpclientCall = new DynamicHttpclientCall(
                "http://shippingapi.ebay.cn/", "GetAPACShippingPackage",
                "http://epacketws.pushauction.net/v3/orderservice.asmx?wsdl");

        Map<String, String> patameterMap = new HashMap<String, String>();

        patameterMap.put("TrackCode", "123");
        patameterMap.put("Version", "123");
        patameterMap.put("APIDevUserID", "123");
        patameterMap.put("APIPassword", "123");
        patameterMap.put("APISellerUserID", "123");
        patameterMap.put("MessageID", "123");
        patameterMap.put("TrackCode", "123");

        String soapRequestData = dynamicHttpclientCall.buildRequestData(patameterMap);
        System.out.println(soapRequestData);

        int statusCode = dynamicHttpclientCall.invoke(patameterMap);
        if(statusCode == 200) {
            System.out.println("调用成功!");
            System.out.println(dynamicHttpclientCall.soapResponseData);
        }
        else {
            System.out.println("调用失败!错误码:" + statusCode);
        }
        
    }

}

      最终运行结果:

      可见最终返回的也是xml格式的数据,这里数据未进行格式化显示和处理



以下是使用Apache HttpClient异步调用WebService的Java代码示例: ```java import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.MessageFactory; import javax.xml.soap.MimeHeaders; import javax.xml.soap.SOAPBody; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPHeader; import javax.xml.soap.SOAPMessage; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactoryConfigurationError; import org.apache.commons.io.IOUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.concurrent.FutureCallback; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; import org.apache.http.impl.nio.client.HttpAsyncClients; import org.apache.http.util.EntityUtils; import org.w3c.dom.Document; import org.xml.sax.SAXException; public class AsyncWebServiceClient { private static final String SOAP_ACTION = "http://tempuri.org/HelloWorld"; private static final String ENDPOINT = "http://localhost/HelloWorldService/HelloWorldService.asmx"; private static final String SOAP_REQUEST = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\n" + " xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" + " <soap:Body>\n" + " <HelloWorld xmlns=\"http://tempuri.org/\" />\n" + " </soap:Body>\n" + "</soap:Envelope>"; public static void main(String[] args) throws Exception { HttpClient httpClient = HttpAsyncClients.createDefault(); CloseableHttpAsyncClient httpclient = (CloseableHttpAsyncClient) httpClient; httpclient.start(); try { HttpPost httpPost = new HttpPost(ENDPOINT); httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8"); httpPost.setHeader("SOAPAction", SOAP_ACTION); StringEntity entity = new StringEntity(SOAP_REQUEST, ContentType.TEXT_XML.withCharset(StandardCharsets.UTF_8)); httpPost.setEntity(entity); Future<HttpResponse> future = httpclient.execute(httpPost, new FutureCallback<HttpResponse>() { @Override public void completed(HttpResponse response) { try { HttpEntity responseEntity = response.getEntity(); String responseBody = EntityUtils.toString(responseEntity); System.out.println(responseBody); Document document = DocumentBuilderFactory.newInstance() .newDocumentBuilder() .parse(IOUtils.toInputStream(responseBody, StandardCharsets.UTF_8)); QName qName = new QName("http://tempuri.org/", "HelloWorldResponse"); SOAPBody soapBody = MessageFactory.newInstance().createMessage().getSOAPBody(); Document responseDocument = soapBody.getOwnerDocument(); SOAPHeader soapHeader = responseDocument.createElementNS("http://schemas.xmlsoap.org/soap/envelope/", "soap:Header"); soapBody.addChildElement(qName).appendChild(responseDocument.createTextNode("Hello World!")); SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(new MimeHeaders(), IOUtils.toInputStream(responseDocument.getDocumentElement().getTextContent(), StandardCharsets.UTF_8)); String soapResponse = IOUtils.toString(soapMessage.getSOAPPart().getContent(), StandardCharsets.UTF_8); System.out.println(soapResponse); } catch (IOException | UnsupportedOperationException | SOAPException | ParserConfigurationException | SAXException | TransformerFactoryConfigurationError | TransformerException e) { e.printStackTrace(); } } @Override public void failed(Exception ex) { ex.printStackTrace(); } @Override public void cancelled() { } }); HttpResponse response = future.get(); System.out.println(response); } finally { httpclient.close(); } } } ``` 以上代码使用Apache HttpClient库异步地调用了一个基于SOAP协议的Web Service,实现了将响应报文解析为SOAP消息的功能。在代码中,我们使用了Java自带的XML解析器和SOAP库,也可以使用第三方库实现相同的功能。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值