我们将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

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

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

    package cn.com.taiji.pos.httpserver; import java.io.BufferedInputStream;import java.io.ByteArrayOutp ...

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

    转自:http://www.cnblogs.com/lanxuezaipiao/archive/2013/05/10/3071584.html 我们将Web Service发布在Tomcat或者其他应 ...

  3. java Webservice(一)HttpClient远程调用

    我们将Web Service发布在Tomcat或者其他应用服务器上后,有很多方法可以调用该Web Service,常用的有两种: 1.通过浏览器HTTP调用,返回规范的XML文件内容      2.通 ...

  4. So easy Webservice 3.使用HttpClient工具调用Webservice接口

    首先,看看webservice服务调用演示: a) 登录http://www.webxml.com.cn b) 单击手机查询服务 c) 选择要调用的方法 例如: getMobileCodeInfo 输 ...

  5. cxf 和 httpclient 客户端调用 webservice 接口

    一.cxf 生成 webservice 客户端 1.接口路径 http://ws.webxml.com.cn/WebServices/WeatherWS.asmx 2.进入你需要放置 webservi ...

  6. asp.net远程调用WebService的两种方法(转载)

    一,静态方法在“解决方案‘项目名’” -> 相应的文件夹,如“Web References” ->右键“添加WEB引用”->在URL里写入地址.二,动态方法在“解决方案‘项目名’” ...

  7. HttpClient远程调用接口

    详细参考这个博文:http://www.cnblogs.com/itliucheng/p/5065619.html 一.get请求: //关键代码就这几行 String urlNameString = ...

  8. SpringBoot使用HttpClient远程调用

    一. Get请求 try { //拼接url url = url+"access_token="+token+"&department_id=1&fetc ...

  9. Java利用Axis远程调用WebService接口

    准备工作: 主要依赖的包: 1.axis.jar 官网:http://axis.apache.org/axis/ 2.jaxrpc.jar 下载地址:http://www.java2s.com/Cod ...

随机推荐

  1. 转:USB枚举

  2. C语言中auto,register,static,const,volatile的区别

    1)auto 这个关键字用于声明变量的生存期为自动,即将不在任何类.结构.枚举.联合和函数中定义的变量视为全局变量,而在函数中定义的变量视为局部变量.这个关键字不怎么多写,因为所有的变量默认就是aut ...

  3. ORA-28002 the password will expire

    ALTER PROFILE DEFAULT LIMIT PASSWORD_LIFE_TIME UNLIMITED;

  4. R的t-test检验

    1.t-test的功能:单因素二水平的假设检验. H0:与我们想过要的结果相反的假设,比如我们想要的是两组数据的差异性,那么这个假设是:两组数据没有差异性. H1或Ha:备择假设,与H0假设相反. 2 ...

  5. Go 语言defer用法

    defer延迟调用: 1.确保调用在函数结束时发生: 2.defer列表为先进后出: 3.通常在Open/Close  Lock/Unlock中使用. defer调用顺序示例: package mai ...

  6. DOCKER 简单操作

    docker ps -a 列出所有镜像 docker start docder_name dcoker start docker_id 运行某个镜像 docker restart docker_nam ...

  7. MySQL使用FEDERATED engine建立代理表

    CREATE TABLE `yndzm` ( `city` varchar(40) DEFAULT NULL COMMENT '市(州)', `county` varchar(60) DEFAULT ...

  8. Qt QT的IO流 QT输入输出

    1. QFile QDataStream 读写文件  二进制读写文件 #include <QApplication> #include <QtGui> #include < ...

  9. dede数据库表结构和dedecms数据库字段说明

    表名:dede_addonarticle (ENGINE=MyISAM/CHARSET=gbk) 说明:Top 字段名 说明描述 具体参数 aid 文章ID mediumint(8) unsigned ...

  10. andriod sdk 模拟器的安装以及root

    安卓模拟器常用的一共2种java sdk 和 bluestacks 蓝手指.前者比较卡,后者貌似不能模拟2g/3g上网.   本文主要是针对java sdk的安装使用,以及root.关于root的意思 ...