java Webservice(一)HttpClient远程调用
我们将Web Service发布在Tomcat或者其他应用服务器上后,有很多方法可以调用该Web Service,常用的有两种:
1、通过浏览器HTTP调用,返回规范的XML文件内容
2、通过客户端程序调用,返回结果可自定义格式
接下来,我利用Eclipse作为开发工具,演示一个Httpclient调用WebService的简单示例
第一种调用见我的另一篇博文:http://www.cnblogs.com/lanxuezaipiao/archive/2013/05/10/3071584.html
步骤如下:
准备工作:用到的jar包有: 下载链接(http://download.csdn.net/detail/lanxuezaipiao/5354480)
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOwAAABNCAIAAAAq8R8IAAAIHUlEQVR4nO2dz2/TZhyH8ydw3WHSkFB36KFSD0jzcaepx50AaULawScOU3dB24EdaBfth2YNtvUwOmDApKmBsi7GWAkptKApFaMHVnXyoTnAlHUIKqCJ6zjxDk7s135/2KntvHb9ffQeGtvv69fJE/u1409dsAAg4xR4d8CyLFksiLJlWZokFARJ6/8lyrz7BWSEOCVe+fKoU4apBxIDkYhN4tKpI4yXTAYSu4DEwBCElbhWqxWLRdrclZmjenNOb87tbErN9WJj+fTm4kcrM0fRQm8bJAYiEUriarU6Pj4+NjZGW6AyM6nv/MEolZlJevPocMJW1/5LFgt9QGiAQbDEtsHHjh1jSXxmUm8uMsr8ybfoayBL7Kori6AxwCBAYsfg48ePMyT+/cyk3rjolNL0BKNgtWl7YmcBGF0ALFgSowazJS5Nj+ubkl1K0xN6Y45YmutFkBiIHZbExWJxDGF2dpa25NVTR/TNor5ZLE1P2H/ghWKwRR1ODLT1vAAAjHgusc2ffFNfP12antDXPyMWusEWdU8swnkdEIp4JP7m/TdK0xP6+mliYRoMAFGJ7ceOefFtRolrLQCAk4Z7JwAgEiAxkHlAYiDzgMRA5gGJgcwDEgOZh7/Ey3Tu3LlTrVZ5dxBIO6mQ2Ox0TLPT7ZrdrtnrdXu9rml2er1uvV5XVbVSrfDuI5Bq+Etcq9U6HQP3uNfr3r9/v9VqKYpSq9V4dzMdyGI/wDV63P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w9TSzcx9ZO/xLnM2GVOYucGDuJPHsQbPv3zCTUPjMS5zNgRJfZnJ4b/iQx/mFp4GGvUJKE/h/QMIMREwuwwqb6o8Jc4lxm7bEnsXYOv4556wZmRJOAvcS4zdp5anvUVCgVBcO+XFCSN9VQ/3+bL2IMjaG+Rr8/o2lmHd3J2xNshUgMUiWPK7fGXOLcZO38t6p6Y9lQ/4ub7JKZG8Zhrx9CQrzc+JwaJI+X2IGPHI2NHrsWSGPkkKfG7/lq8EhOjeMFrp56o4d+b2PbEEXJ7kLHjkbEbpcSE9QeunQHWomfCkGPimHJ7kLHjlbEbTmLSC+Lm48MJYhRvGIndixO+0QdW0WnYf+2MkuqLKbcHGTsuGTtyrf7WOJ8vemJHfKqff/NJJ3aEE6bgtVPf5gKuM+lT8CqO4kn1xZTbg4xd+klxui0iMW0ZZOzSz4GVOK4fFiFjl34OosSx5vb4XyeGjB0QEf4SA0BEQGIg84DEQOYBiYHMw19iyNgBEUmFxJCxA6LAX+K8ZuxivfKb8lBdwt3jL3FeM3ZplZiWh4sy98BLnNeMXQp/g2Pn4aLMTRb+Euc1Y5dCiW3Yv3JHmZsU/CXOa8aOfe8oOt37lAPidF8eCesPvTWcBCSOKUtHg7/Eec3YBTfr+diRG5UJ030b4s/P0VojkqjEiTwDDzJ2vDJ2xPgQJXpE7Cb6kpoMJXXeE0vBdtlJ74kjZOloQMaOV8aOJjFTu5glJpKkxNGydDQgY8crY0cZTrCHDaGGE+Qjwz6HEyHTcuy5MWXpaEDGjlfGLujEDkmdUR5fRz+xw48MtNYo76bbm5BpuZFk6WhAxi4L0AYAAQODIVtLjoSvvEHGLp0gMXnPkIM2fX+tjYikfxSHjF1aQY7P2AUM0vT9tZY0sWbpaPC/TgwZOyAi/CUGgIiAxEDm+R/qvD5g3fOWmgAAAABJRU5ErkJggg==" alt="" />
第一步:新建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);
} } }
最终运行结果:
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAsIAAAA2CAIAAABC7GioAAAOwUlEQVR4nO2d26HrKAxFXRcFUQ8lTBU042I8H34JtAXCjvM4d6+fucOxQRKSECSxp6XkP0IIIYQQH9NCCCGEEHIJlhGEEEIIuQjLCEIIIYRchGUEIYQQQi4yWkbkOE3TNMV8ZbDt5qu3v4A5hZeOvveX4zSFNH9tn1flEKb6RtPNKWweNdqDMfot9/5H+HwUKz4vki86kNfl+H6pq9BuNP493qbmB+z5Xl8SPn/pNOLWivJRb331WrjkOE0xL3MKcjXalrf+QHAdxH2+nYfLiBE1DZ/J0WWgY5GRU9IY/eWa3gL5krt8kqq/vAj8GhOt/EJiAV5npf4Hl/o5Be03sPFphH++afBCTRhH/sZmnj8GK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EOhkFKs3Q6J6itI/QLpMsIZ7IbXYSMfbUJNaTm1fDS+G6EzSHcpBW4zFB1IThSbgLvpwq6S4RTXuj82Ry7sOYJ5oG4c8xBHXbLI+RALrb/xFLNyOHg7lB1kRWM6mqcRhc+io1fk3i6zm8LjLT24XQzfuf2N/jmwdvRzCJ9iSV5HWaS2zi5JTedY7Wv4FTmf4LO6u0f3nNP8AWC2eZuaNwd6RM6P+SfLCPI6isC+cuz7D/Mry/OvyPkEP1JG/CMw29SwjCB/geJQjkcRI/zKIvErcj4By4ivgtmmgmUEIYQQQn4NlhGEEEIIuQjLCEIIIYRchGUEIYQQQi7CMoIQQgghF2EZQQghhJCLsIwghBBCyEX+B0wSWlZPuFtOAAAAAElFTkSuQmCC" alt="" />
package httpclient;
import java.io.IOException;
import java.net.URLEncoder;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
public class HttpClientTest {
public static void main(String[] args) throws Exception{
String url = "/webservices/DomesticAirline.asmx/getDomesticAirlinesTime";
String host = "www.webxml.com.cn";
String param = "startCity="+URLEncoder.encode("杭州", "utf-8")+"&lastCity=&theDate=&userID=";
HttpClient httpClient = new HttpClient();
httpClient.getHostConfiguration().setHost(host, 80, "http");
HttpMethod method = getMethod(url, param);
//HttpMethod method = postMethod(url);
httpClient.executeMethod(method);
String response = method.getResponseBodyAsString();
//String response = new String(method.getResponseBodyAsString().getBytes("ISO-8859-1"));
System.out.println(response);
}
private static HttpMethod getMethod(String url,String param) throws IOException{
GetMethod get = new GetMethod(url+"?"+param);
get.releaseConnection();
return get;
}
private static HttpMethod postMethod(String url) throws IOException{
PostMethod post = new PostMethod(url);
post.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=gbk");
NameValuePair[] param = { new NameValuePair("startCity","杭州"),
new NameValuePair("lastCity","沈阳"),
new NameValuePair("userID",""),
new NameValuePair("theDate","") } ;
post.setRequestBody(param);
post.releaseConnection();
return post;
}
}
如果PostMethod提交的是中文字符,需要加上相应的编码格式: post.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=gbk");
如果GetMethod提交的参数有中文字符,需要先转换成utf-8格式: URLEncoder.encode("杭州", "utf-8");
1.拳头之Get/Post
拳头是最基本的一重武器,也是最重要的,好比练武之人必须先扎稳马步。
- HttpClient httpclient=new HttpClient();//创建一个客户端,类似打开一个浏览器
- GetMethod getMethod=new GetMethod("http://www.blablabla.com");//创建一个get方法,类似在浏览器地址栏中输入一个地址
- int statusCode=httpclient.executeMethod(getMethod);//回车——出拳!
- System.out.println("response=" + getMethod.getResponseBodyAsString());//察看拳头命中情况,可以获得的东西还有很多,比如head, cookies等等
- getMethod.releaseConnection();//释放,记得收拳哦
2.孔雀翎之支持https
如何支持https?
- static{
- Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443);
- Protocol.registerProtocol("https", easyhttps);
- }
在执行具体的http method之前,暗中将https协议注册一把,如孔雀翎暗藏玄机,毙敌于无形。记住,官方的binary发行版本没有ssl的contribute包,方法一是下载源代码版本来打造你的孔雀翎。
3.多情环之cookies
常道人老多情,其实是记忆太多,所以情之所至,正如cookies甜心,无论你走到那,总把你牵挂:
- HttpClient httpclient=new HttpClient();
- httpclient.getParams().setCookiePolicy(CookiePolicy.RFC_2109);//RFC_2109是支持较普遍的一个,还有其他cookie协议
- HttpState initialState = new HttpState();
- Cookie cookie=new Cookie();
- cookie.setDomain("www.balblabla.com");
- cookie.setPath("/");
- cookie.setName("多情环");
- cookie.setValue("多情即无情");
- initialState.addCookie(cookie);
- httpclient.setState(initialState);
- ...
4.离别钩之解构cookies
多情环的反面即离别钩,钩出,敌之身体某个部件即要与身体别离,端的是无情:
- ...//执行了某些get/post方法后
- Cookie[] cookies = httpclient.getState().getCookies();
- System.out.println("Present cookies: ");
- for (int i = 0; i < cookies.length; i++) {//循环结构零部件
- System.out.println(" - " + cookies[i].toExternalForm());
- System.out.println(" - domain=" + cookies[i].getDomain());
- System.out.println(" - path=" + cookies[i].getPath());
- ...
- }
5.霸王抢之post参数
枪,长兵器之王,诸多名将均使一杆或金或银命名的名枪,比如岳飞。post方法在提交参数对时,犹如灵蛇出洞:
- PostMethod postMethod = new PostMethod("http://www.saybot.com/postme");
- NameValuePair[] postData = new NameValuePair[2];
- postData[0] = new NameValuePair("武器", "枪");
- postData[1] = new NameValuePair("什么枪", "神枪");
- postMethod.addParameters(postData);
- ...//出枪吧
6.七星碧玉刀之支持代理(proxy)
代理,非常重要,尤其在局域网横行的年头,没有代理,你在公司上不了QQ,没有代理,google不了网页快照,代理之威,可比七星碧玉刀,无刀,在局域网和开发当中,一切白搭:
- HttpClient httpclient=new HttpClient();
- httpClient.getHostConfiguration().setProxy("192.168.0.1", 9527);
- httpClient.getParams().setAuthenticationPreemptive(true);//重要!!!告诉httpclient,使用抢先认证,否则你会收到“你没有资格”的恶果
- /*
- 这一步也至关重要,MyProxyCredentialsProvider实现了org.apache.commons.httpclient.auth.CredentialsProvider接口,
- 返回代理的credential(username/password)*/
- httpClient.getParams().setParameter(CredentialsProvider.PROVIDER, new MyProxyCredentialsProvider());
- httpClient.getState().setProxyCredentials(
- new AuthScope("192.168.0.1",
- AuthScope.ANY_PORT, //任意端口哦,可要小心
- AuthScope.ANY_REALM),//任意域哦,可要小心
- new UsernamePasswordCredentials("username",//proxy的用户名
- "password"));//proxy的密码
...
java Webservice(一)HttpClient远程调用的更多相关文章
- Java WebService接口生成和调用 图文详解>【转】【待调整】
webservice简介: Web Service技术, 能使得运行在不同机器上的不同应用无须借助附加的.专门的第三方软件或硬件, 就可相互交换数据或集成.依据Web Service规范实施的应用之间 ...
- Httpclient远程调用WebService示例(Eclipse+httpclient)
package cn.com.taiji.pos.httpserver; import java.io.BufferedInputStream;import java.io.ByteArrayOutp ...
- Httpclient远程调用WebService示例
我们将Web Service发布在Tomcat或者其他应用服务器上后,有很多方法可以调用该Web Service,常用的有两种: 1.通过浏览器HTTP调用,返回规范的XML文件内容 2.通 ...
- WebService与RMI(远程调用方式实现系统间通信)
前言 本文是<分布式java应用基础与实践>读书笔记:另外参考了此博客,感觉讲的挺好的,尤其是其中如下内容: 另外,消息方式实现系统间通信本文不涉及.RMI则只采用spring RMI框架 ...
- java项目中rmi远程调用实例
1.创建一个学生实体类Student.java: package com.RMIdemo.entity; @SuppressWarnings("serial") public cl ...
- [置顶]
Java WebService接口生成和调用 图文详解
webservice简介: Web Service技术, 能使得运行在不同机器上的不同应用无须借助附加的.专门的第三方软件或硬件, 就可相互交换数据或集成.依据Web Service规范实施的应用之间 ...
- Java模拟http请求远程调用接口工具类
package ln; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamRea ...
- java Webservice(一)HttpClient使用(二)
HTTP 协议可能是现在 Internet 上使用得最多.最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源.虽然在 JDK 的 java.net 包中已经提供了 ...
- java Webservice(一)HttpClient使用(一)
1.拳头之Get/Post拳头是最基本的一重武器,也是最重要的,好比练武之人必须先扎稳马步. java 代码 HttpClient httpclient=new HttpClient();//创建一个 ...
随机推荐
- 在AE10.1环境下调试其他版本的程序
不同人的可能使用的开发环境不一样,使用SDK版本也不一样,比如用ArcEngine9.3开发的程序在ArcEngine10.1下就不能运行,需要重新调试,才能运行. 这里的例子程序是其他网友在ArcE ...
- 把mysql数据库生成数据字典,直接可用
便于查看数据库表.字段,做一个数据字典是很有必要的,下面只需要简单更改下配置就可以用了,样式也是挺好的. <?php header('content-type:text/html;charset ...
- Codeforces 417D Cunning Gena(状态压缩dp)
题目链接:Codeforces 417D Cunning Gena 题目大意:n个小伙伴.m道题目,每一个监视器b花费,给出n个小伙伴的佣金,所须要的监视器数,以及能够完毕的题目序号. 注意,这里仅仅 ...
- 运行php程序时,浏览器跳出打开和保存提示框
解决办法:将php.ini文件复制到 C:\Windows
- python中in在list和dict中查找效率比较
转载自:http://blog.csdn.net/wzgbm/article/details/54691615 首先给一个简单的例子,测测list和dict查找的时间: ,-,-,-,-,,,,,,] ...
- TopCoder SRM624 BuildingHeightEasy 题解
本题题意就是求有一组建筑物,问把这些建筑物的M个都统一到同一高度.须要的最小改动高度是多少? 题意隐含的意思就是由于是建筑物,所以不能降低,仅仅能添加了. 本题能够使用暴力搜索,由于数据量少. 可是事 ...
- C-main函数剖析。
对于main函数.我想不论什么一个接触到C语言的都不会陌生,可是说起main()函数有參数,你可能会产生非常多疑问了. 首先,我们来看下msdn,这个里面对main()函数有具体的说明. 在这里,我们 ...
- Windows下安装Redmine 2.5.2不全然指南
我决定在项目中引入Redmine来管理开发任务和计划,至于Redmine的优点,请问度娘或者脑补一下. 互联网搜索到的.基本上都是旧版本号的. 1.2.1 的最多,我要新的啊,所以仅仅好自己来啦. 本 ...
- DIY手机万能红外遥控器
DIY手机万能红外遥控器 1.手机安装软件:遥控精灵 2.红外二极管两个(旧的遥控器里面可以拆) 3.耳机的插头一个 步骤:首选讲两个二极管的正负相接(即a二极管的正极连接b二极管的负极,a二极管的负 ...
- 腾讯云-Linux 基础入门
Linux 基础入门 目录操作 任务时间:5min ~ 10min 创建目录 使用 mkdir 命令创建目录 mkdir $HOME/testFolder # $HOME 当前用户的家目录 root ...