在上一篇博客 WebService快速入门(附Demo演示)演示了编写简单的服务端、客户端,本篇博客将演示WebService
调用的常见两类方式。
一、客户端方式
这里通过jdk自带的wsimport命令演示。
1、新建一个普通java项目
2、在src目录执行wsimport
命令
执行命令wsimport -p cn.hestyle.mobile -s . http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl
3、编写客户端调用代码
package cn.hestyle.test;
import cn.hestyle.mobile.MobileCodeWS;
import cn.hestyle.mobile.MobileCodeWSSoap;
/**
* description: 测试生成的客户端
*
* @author hestyle
* @version 1.0
* @className WebService Project 02 Client->Test01
* @date 2019-12-08 11:48
**/
public class Test01 {
public static void main(String[] args) {
//1、创建服务
MobileCodeWS mobileCodeWS = new MobileCodeWS();
//2、通过服务获取端口
MobileCodeWSSoap soap = mobileCodeWS.getPort(MobileCodeWSSoap.class);
//3、调用端口的getMobileCodeInfo方法,第一个参数为11位长的电话号码(注意修改,我打了码)
String info = soap.getMobileCodeInfo("159****0405", null);
System.out.println(info);
}
}
执行main方法,控制台输出:
二、拼接参数发起http请求
第二类方法是在代码中拼接请求参数,直接发起http
请求。这里通过java中的HTTPURLConnection
类进行演示,其它的编程语言也可以实现,因为WebService
使用xml格式传输数据,与平台、开发语言无关。
package cn.hestyle.test;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* description: 使用java.net.HttpURLConnection发送POST网络请求
*
* @author hestyle
* @version 1.0
* @className WebService Project 02 Client->Demo01
* @date 2019-12-08 12:21
**/
public class Demo01 {
public static void main(String[] args) throws Exception {
//1、创建url
URL url = new URL("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
//2、设置可以写请求数据
conn.setDoOutput(true);
//设置请求头
conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
OutputStream os = conn.getOutputStream();
//第一个参数为11位长的电话号码(注意修改,我打了码)
os.write(getXML("159****0405").getBytes());
//3、获取响应字符串
int code = conn.getResponseCode();
System.out.println("响应状态码:" + code);
if(200 == code){
//4、读取响应数据
InputStream is = conn.getInputStream();
InputStreamReader reader = new InputStreamReader(is,"UTF-8");
BufferedReader br = new BufferedReader(reader);
String line = null;
while((line = br.readLine()) != null){
System.out.println(line);
}
br.close();
}
os.close();
}
/**
* 传入电话号码,拼接请求参数
* @param tel 电话号码
* @return 拼接好的xml格式请求字符串
*/
public static String getXML(String tel){
return "<?xml version=\"1.0\" encoding=\"utf-8\"?>"+
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"" +
" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
"<soap:Body>" +
"<getMobileCodeInfo xmlns=\"http://WebXml.com.cn/\">" +
"<mobileCode>" + tel + "</mobileCode>" +
"<userID></userID>" +
"</getMobileCodeInfo>" +
"</soap:Body>" +
"</soap:Envelope>";
}
}
执行main方法,控制台输出:
以上就是WebService
调用的常见两类方式,即客户端访问
、http请求访问
,它们都与平台、开发语言无关,只不过我使用了java开发语言进行演示。