Httpclient远程调用WebService示例

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

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

第一步:新建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格式的数据,这里数据未进行格式化显示和处理

原文地址:http://www.cnblogs.com/lanxuezaipiao/archive/2013/05/10/3071584.html

时间: 2024-12-24 22:08:04

Httpclient远程调用WebService示例的相关文章

AXIS2远程调用WebService示例(Eclipse+AXIS)

转自:http://www.cnblogs.com/lanxuezaipiao/archive/2013/05/10/3071584.html 我们将Web Service发布在Tomcat或者其他应用服务器上后,有两种方法可以调用该Web Service: 1.通过浏览器调用,返回规范的XML文件      2.通过客户端程序调用,返回结果可自定义格式 接下来,我利用Eclipse J2EE作为开发工具,演示一个Axis调用WebService的简单示例      第一种调用见我的另一篇博文:

java Webservice(一)HttpClient远程调用

目前知道的三种主流的Web服务实现方案为:REST:表象化状态转变 (软件架构风格)SOAP:简单对象访问协议 XML-RPC:远程过程调用协议 下面分别作简单介绍: REST:表征状态转移(Representational State Transfer),采用Web 服务使用标准的 HTTP 方法 (GET/PUT/POST/DELETE) 将所有 Web 系统的服务抽象为资源,REST从资源的角度来观察整个网络,分布在各处的资源由URI确定,而客户端的应用通过URI来获取资源的表征.Http

httpClient 远程调用接口,java8新特性Optional

import java.util.Optional; /** * java 8新特性 * * @author wang-xiaoming * @date 2019年7月2日 */ public class OptionalTest { public static void ofNullable(String value) { Optional<String> opt = Optional.ofNullable(value); System.out.println("[ofNullab

SpringBoot使用HttpClient远程调用

一. Get请求 try { //拼接url url = url+"access_token="+token+"&department_id=1&fetch_child=1"; //解决证书明匹配问题 SSLSocketFactory.getSocketFactory().setHostnameVerifier(new AllowAllHostnameVerifier()); //根据地址获取请求 HttpGet request = new Http

Httpurlconnection远程调用webservice

问题: c.sun.xml.internal.messaging.saaj.soap.SOAPVersionMismatchException: Cannot crte message: incorrect content-type for SOAP version. Got: application/soap+xmlcharset=utf-8; action="" Expected: text/xml 解决:设置soap协议为1.2即可 在springboot中添加一下代码 //so

Android使用ksoap2-android调用WebService学习

转自 Android使用ksoap2-android调用WebService学习 之前主要做客户端UI交互,很少处理数据和接触服务端,但现在的移动设备根本不可能离得开网络连接,数据的交换.最近学习的是在android端如何去调用远程WebService,都说WebService是一种基于SOAP协议的远程调用标准,对于这个协议理解不深,知道webservice可以将不同操作系统平台.不同语言.不同技术整合到一块,android SDK没有直接调用webservice的库,最常用的是借助ksoap

C#动态调用webService出现 基础连接已经关闭: 未能为 SSL/TLS 安全通道建立信任关系。

在远程调用WebService时出现下面的情况: 这种情况一般是由于证书有问题时出现,如果在浏览器中打开是这种情况: 解决方法新建一个类,代码如下: 1 public static class CertificateTrust 2 { 3 4 public static void SetCertificatePolicy() 5 { 6 ServicePointManager.ServerCertificateValidationCallback 7 += RemoteCertificateVa

Android使用ksoap2-android调用WebService

现在的移动设备根本不可能离得开网络连接,数据的交换.最近学习的是在android端如何去调用远程WebService,都说WebService是一种基于SOAP协议的远程调用标准,对于这个协议理解不深,知道webservice可以将不同操作系统平台.不同语言.不同技术整合到一块,android SDK没有直接调用webservice的库,最常用的是借助ksoap2-android这个第三方SDK,点击打开链接,然后和其他第三方jar包一样导入android项目中即可. 1,定义webservic

WebService与RMI(远程调用方式实现系统间通信)

前言 本文是<分布式java应用基础与实践>读书笔记:另外参考了此博客,感觉讲的挺好的,尤其是其中如下内容: 另外,消息方式实现系统间通信本文不涉及.RMI则只采用spring RMI框架来实现效果,更多的则是来讲讲webService及效果. RMI(Remote Method Invocation) ----> spring RMI(配置及实现直接参考spring文档,已经很详细了) spring RMI工作原理图如下: RMI代码结构图: 服务端代码 接口Business.java