精华内容
下载资源
问答
  • webservice接口调用

    2015-12-04 17:48:54
    webservice接口调用
  • WebService接口调用

    千次阅读 2017-11-02 10:40:01
    最近项目中有朋友咨询我webService接口的调用,在这里...一、webService接口调用工具类 public class WebService { private WebService() { throw new IllegalAccessError("CallWebServiceInterface class"); }

    最近项目中有朋友咨询我webService接口的调用,在这里总结并分享一下,我对webService方法的调用。


    一、webService接口调用工具类

    public class WebService {
    	private WebService() {
    		throw new IllegalAccessError("CallWebServiceInterface class");
    	}
    
    	public static <E> E getWebServiceClient(String url, Class<E> clazz, int connectionTimeout, int receiveTimeout) {
    		JaxWsProxyFactoryBean proxy = new JaxWsProxyFactoryBean();
    		proxy.setServiceClass(clazz);
    		proxy.setAddress(url);
    		@SuppressWarnings("unchecked")
    		E client = (E) proxy.create();
    		// 配置超时时间
    		Client clientProxy = ClientProxy.getClient(client);
    		HTTPConduit conduit = (HTTPConduit) clientProxy.getConduit();
    		HTTPClientPolicy policy = new HTTPClientPolicy();
    		policy.setConnectionTimeout(connectionTimeout); // 连接超时时间
    		policy.setReceiveTimeout(receiveTimeout);// 请求超时时间
    		conduit.setClient(policy);
    		return client;
    	}
    
    	public static <E> E getWebServiceClient(String url, Class<E> clazz) {
    		return getWebServiceClient(url, clazz, 5000, 5000);
    	}
    }


    二、webService服务接口

    @WebService(targetNamespace = "http://biz.cos.interfaces.ccs.sf.com/")
    public interface webServiceTest{
    	
    
    	@WebMethod
    	List<String> queryAddressByPhone(String args);
    
    }

    注意:
    1、webService注解上的targetNamespace是接口提供方的分包地址,获取方式可以直接访问webService接口地址返回的XML文件中获取;
    2、接口中的方法名必须带webMethod注解,并且接口方法必须与提供方的接口一模一样;


    三、WebService接口的调用

    参数详解:
    1、url为接口供应商提供的webService接口地址
    2、args为webService方法需求的参数

    public List<String> queryAddressByPhone(String url , String args) {
    	webServiceTest client = WebService.getWebServiceClient(url, webServiceTest.class);
    	List<String> Result = client.queryAddressByPhone(args);
    	return Result;
    }











    展开全文
  • Webservice接口调用

    千次阅读 2019-03-09 16:07:58
    web service分两大类架构一种是基于soap协议的(wsdl结尾的接口),另外一种就是基于restful思想的,由于...1.先来看soap风格的webservice接口调用的步骤。 直接点击SOAP按钮–图里画出来了,弹出new soap proje...

    web service分两大类架构一种是基于soap协议的(wsdl结尾的接口),另外一种就是基于restful思想的,由于restful api接口(http地址的接口,但是请求报文为xml/json)的设计思想,后者国外商业应用更多。例如谷歌推特提供的api接口。

    1.先来看soap风格的webservice接口调用的步骤。

    直接点击SOAP按钮–图里画出来了,弹出new soap project的对话框。在Initial WSDL中浏览webservice接口服务端生成的wsdl文件。ProjectName可以自定义,软件也会自动在你浏览了wsdl文件后填上内容。点击ok.
    在这里插入图片描述在这里插入图片描述
    进入设置入参的界面。还是自动生成的入参报文,只需要输入入参,点击绿三角运行,就完成了接口调用。在右侧现实出回参XML
    在这里插入图片描述
    2.再来看rest风格调用webservice接口的步骤
    同soap新建一样,这里点击rest,new rest project,这里的URI就是服务方提供的接口地址。点击ok
    在这里插入图片描述
    接口地址会被自动拆分成三部分,其中parameters是空。通过选择请求的方式-Method,已经选择参数的类型Media Type设置入参类型和入参的内容。如图示。都设置好,并输入了入参信息,点击绿三角,调用接口。可在右侧看到返回值。返回值也是有几种:xml,json,Html等。
    在这里插入图片描述
    总结区别:

    1.soap风格依赖与wsdl这个接口服务描述文件,通过这个wsdl文件,可以把暴露的接口中的所有方法显示出来,然后在列表中选择你要调用的方法,输入参数就可以了,相当于由wsdl只能定位到接口/类上面,具体不到那个方法。而rest风格的URI方式直接定位到方法。

    2.soap风格没有设置请求方式是get,post,还是delete,put。因为soap默认为post请求。而rest是可以自己设定请求类型的。

    3.soap风格参数底层传输固定是出入参固定是xml格式的。没有json等其他形式的参数格式。rest风格的出入参数的数据类型可以是xml,json等常用格式,入参没有底层生成的任何东西,全部自己搞定,xml还是json格式,要严格符合选中的数据类型才行。

    展开全文
  • 近来由于项目需要,需要用到手机短信验证码的功能,其中最主要的是用到了第三方提供的短信平台接口WebService客户端接口,下面我把我在项目中用到的记录一下,以便给大家提供个思路,由于本人的文采有限,还请大家...

    近来由于项目需要,需要用到手机短信验证码的功能,其中最主要的是用到了第三方提供的短信平台接口WebService客户端接口,下面我把我在项目中用到的记录一下,以便给大家提供个思路,由于本人的文采有限,还请大家见谅!

    一:首先上几张案例截图,以便大家可以了解一下短信验证码的流程,这里我在做的过程中也参考了很多网站的短信验证码,比如:58同城,汽车之家等。

    1.点击获取验证码之前的样式:

    2.输入正确的手机号后点击获取验证码之后的样式:

    3.如果手机号已经被注册的样式:

    4.如果一个手机号一天发送超过3次就提示不能发送:

    二:前台的注册页面的代码:reg.jsp

     

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%@taglib prefix="s" uri="/struts-tags"%>
    <%@page import="cn.gov.csrc.base.action.FindAllData"%>
    <%
    	String path = request.getContextPath();
    	String basePath = request.getScheme() + "://"
    			+ request.getServerName() + ":" + request.getServerPort()
    			+ path + "/";
    %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <head>
    <base href="<%=basePath%>">
    <title>中国证券会证券期货违法违规举报中心-注册</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <link rel="shortcut icon" type="image/x-icon" href="<%=request.getContextPath()%>/images/favicon.ico" />
    <link rel="stylesheet" type="text/css"
    	href="<%=request.getContextPath()%>/css/main.css">
    <link
    	href="<%=request.getContextPath()%>/formValidator1/style/validator.css"
    	rel="stylesheet" type="text/css" />
    <style type="text/css">
    button {
    	background: #F0F0F0 repeat-x;
    	padding-top: 3px; 
    	border-top : 1px solid #708090;
    	border-right: 1px solid #708090;
    	border-bottom: 1px solid #708090;
    	border-left: 1px solid #708090;
    	width: auto;
    	line-height: 12pt; 
    	font-size : 10pt;
    	cursor: hand;
    	font-size: 10pt;
    	border-top: 1px solid #708090;
    }
    </style>
    <script src="<%=request.getContextPath()%>/js/jquery-1.7.2.min.js"
    	type="text/javascript"></script>
    <script src="<%=request.getContextPath()%>/formValidator1/formValidator-4.0.1.js"
    	type="text/javascript"></script>
    <script src="<%=request.getContextPath()%>/formValidator1/formValidatorRegex.js"
    	type="text/javascript"></script>
    <script src="<%=request.getContextPath()%>/js/register.js"
    	type="text/javascript"></script>
    <script src="<%=request.getContextPath()%>/js/sms.js"
    	type="text/javascript"></script>
    <script type="text/javascript">
    	function changeCheckNum() {
    		var checkNumImage_ = document.getElementById("checkNumImage");
    		checkNumImage_.src = "${pageContext.request.contextPath}/image.jsp?timeStamp="+ new Date().getTime();
    	}
    </script>
    <script type="text/javascript">
    	var msg = "${message}";
    	if (msg != "") {
    		alert(msg);
    	}
    </script>
    </head>
    <body>
    	<%@include file="/statics/top.jspf"%>
    	<div class="center_division">
    		<div class="center_body">
    			<div class="center_menu">
    				<font color="#000000">当前位置:</font>
    				<a href="<%=request.getContextPath()%>/statics/reg.jsp"><font color="#000000">用户注册</font></a>
    			</div>
    		</div>
    		<div class="center_body_menu">
    			<s:form action="RegisterAction_register" id="form1" name="form1" method="post" namespace="/">
    				<table id="tb">
    					<tr>
    						<td colspan="3" align="center" bgcolor="#DDDFE1">举报人基本信息</td>
    					</tr>
    					<tr>
    						<td align="center" width="30%">    <img src="images/new_reg_xing.gif"/>用户名:</td>
    						<td align="center" width="40%">
    							<s:textfield name="username" id="username" cssStyle="width:160px;height:24px;" onblur="checkusername()"/>
    						</td>
    						<td align="left" width="30%">
    							<span id="usernameTip">
    								<s:fielderror cssStyle="color:red;padding-left:10px;">
    									<s:param>username</s:param>
    								</s:fielderror>
    							</span>
    						</td>
    					</tr>
    					<tr>
    						<td align="center" width="30%"><img src="images/new_reg_xing.gif"/>登录密码:</td>
    						<td align="center" width="40%">
    							<s:password name="password" id="password" cssStyle="width:160px;height:24px;" onblur="checkpassword()"/>
    						</td>
    						<td align="left" width="30%">
    							<span id="passwordTip">
    								<s:fielderror cssStyle="color:red;padding-left:10px;">
    									<s:param>password</s:param>
    								</s:fielderror>
    							</span>
    						</td>
    					</tr>
    					<tr>
    						<td align="center" width="30%"><img src="images/new_reg_xing.gif"/>确认密码:</td>
    						<td align="center" width="40%">
    							<s:password name="passwordRepeat" id="passwordRepeat" cssStyle="width:160px;height:24px;" onblur="checkpasswrodb()"/>
    						</td>
    						<td align="left" width="30%">
    							<span id="passwordRepeatTip">
    								<s:fielderror cssStyle="color:red;padding-left:10px;">
    									<s:param>passwordRepeat</s:param>
    								</s:fielderror>
    							</span>
    						</td>
    					</tr>
    					<tr>
    						<td align="center" width="30%"><img src="images/new_reg_xing.gif"/>姓        名:</td>
    						<td align="center" width="40%">
    							<s:textfield name="nickname" id="nickname" cssStyle="width:160px;height:24px;" onblur="checknickname()"/>
    						</td>
    						<td align="left" width="30%">
    							<span id="nicknameTip">
    								<s:fielderror cssStyle="color:red;padding-left:10px;">
    									<s:param>nickname</s:param>
    								</s:fielderror>
    							</span>
    						</td>
    					</tr>
    					<tr>
    						<td align="center" width="30%">性        别:</td>
    						<td align="center" width="40%">
    							<s:radio list="#application.dataMap.get('10001')" name="jbSex" cssStyle="height:24px;"/>
    						</td>
    						<td align="left" width="30%"></td>
    					</tr>
    					<tr>
    						<td align="center" width="30%">联系地址:</td>
    						<td align="center" width="40%">
    							<s:textfield name="jbAddress" id="jbAddress" cssStyle="width:160px;height:24px;" />
    						</td>
    						<td align="left" width="30%">
    							<span id="jbAddressTip">
    								<s:fielderror cssStyle="color:red;padding-left:10px;">
    									<s:param>jbAddress</s:param>
    								</s:fielderror>
    							</span>
    						</td>
    					</tr>
    					<tr>
    						<td align="center" width="30%"><img src="images/new_reg_xing.gif"/>联系手机:</td>
    						<td align="center" width="40%">
    							<s:textfield id="jbPhone" name="jbPhone" cssStyle="width:160px;height:24px;" onblur="checkjbPhone()"/>
    						</td>
    						<td align="left" width="30%">
    							<span id="jbPhoneTip">
    								<s:fielderror cssStyle="color:red;padding-left:10px;">
    									<s:param>jbPhone</s:param>
    								</s:fielderror>
    							</span>
    						</td>
    					</tr>
    					<tr>
    						<td align="center"><img src="images/new_reg_xing.gif"/>短信验证码:</td>
    						<td align="left" colspan="2" style="padding-left: 112px;">
    							<s:textfield id="SmsCheckCode" name="SmsCheckCode" cssStyle="width:80px;height:24px;" maxLength="6" />
    							<span><input type="button" id="btnSendCode" name="btnSendCode" value="免费获取验证码" onclick="sendMessage()" /></span>
    							<span id="SmsCheckCodeTip">
    								<s:fielderror cssStyle="color:red;padding-left:10px;">
    									<s:param>SmsCheckCodeTip</s:param>
    								</s:fielderror>
    							</span>
    						</td>
    					</tr>
    					<tr>
    						<td align="center" width="30%"><img src="images/new_reg_xing.gif"/>证件类型:</td>
    						<td align="center" width="40%">
    						<s:select list="#application.dataMap.get('10002')" label=""
    								headerKey="" headerValue="--请选择--" value="1" listValue="value" onchange="enableCredentialsCode(this)"
    								name="jbCredentialsName" id="jbCredentialsName" cssStyle="width:160px;height:24px;"/>
    						</td>
    						<td align="left" width="30%">
    							<s:fielderror cssStyle="color:red;padding-left:10px;">
    								<s:param>jbCredentialsName</s:param>
    							</s:fielderror>
    						</td>
    					</tr>
    					<tr>
    						<td align="center" width="30%"><img src="images/new_reg_xing.gif"/>证件号码:</td>
    						<td align="center" width="40%">
    							<s:textfield name="jbCredentialsCode" id="jbCredentialsCode" cssStyle="width:160px;height:24px;" onblur="checkjbCredentialsCode()"/>
    						</td>
    						<td align="left" width="30%">
    							<span id="jbCredentialsCodeTip">
    								<s:fielderror cssStyle="color:red;padding-left:10px;">
    									<s:param>jbCredentialsCode</s:param>
    								</s:fielderror>
    							</span>
    						</td>
    					</tr>
    					<tr>
    						<td align="center" width="30%">单位名称:</td>
    						<td align="center" width="40%">
    							<s:textfield name="jbCompanyName" id="jbCompanyName" cssStyle="width:160px;height:24px;" />
    						</td>
    						<td align="left" width="30%">
    							<span id="jbCompanyNameTip">
    								<s:fielderror cssStyle="color:red;padding-left:10px;">
    									<s:param>jbCompanyName</s:param>
    								</s:fielderror>
    							</span>
    						</td>
    					</tr>
    					<tr>
    						<td align="center" width="30%"><img src="images/new_reg_xing.gif"/>所在地区:</td>
    						<td align="center" width="40%">
    						<s:select list="#application.dataMap.get('10003')" label=""
    								headerKey="" headerValue="--请选择--" listKey="key"
    								cssStyle="width:160px;height:24px;" listValue="value" id="jbSourceArea"
    								name="jbSourceArea" onblur="checkjbSourceArea()"/>
    						</td>
    						<td align="left" width="30%">
    							<span id="jbSourceAreaTip">
    								<s:fielderror cssStyle="color:red;padding-left:10px;">
    									<s:param>jbSourceArea</s:param>
    								</s:fielderror>
    							</span>
    						</td>
    					</tr>
    					<tr>
    						<td align="center" width="30%">    <img src="images/new_reg_xing.gif"/>验证码:</td>
    						<td align="center" width="40%">
    							<s:textfield id="checkNum" name="checkNum" cssStyle="width:60px;height:24px;" onblur="checkNumber()" maxLength="4"/>
    							<img id="checkNumImage" src="${pageContext.request.contextPath}/image.jsp">
    							<a onClick="changeCheckNum()" title="点击换一张" style="cursor:hand;"> 换一张</a>
    						</td>
    						<td align="left" width="30%">
    							<span id="checkNumTip">
    								<s:fielderror cssStyle="color:red;padding-left:10px;">
    									<s:param>checkNumTip</s:param>
    								</s:fielderror>
    							</span>
    						</td>
    					</tr>
    					<tr>
    						<td colspan="3" style="vertical-align: top; padding-top: 5px;padding-bottom: 5px;">
    							<input type="submit" value="注册" style="width:50px; height:24px;"/>
    							  
    							<input type="reset" value="重置" style="width:50px; height:24px;"/>
    						</td>
    					</tr>
    				</table>
    			</s:form>
    		</div>
    	</div>
    	<%@include file="/common/buttom.jspf"%>
    </body>
    </html>
    


    三:前台获取短信验证码的js:sms.js

     

     

    var InterValObj; //timer变量,控制时间
    var count = 120; //间隔函数,1秒执行
    var curCount;//当前剩余秒数
    var code = ""; //验证码
    var codeLength = 6;//验证码长度
    
    function sendMessage() {
    	curCount = count;
    	var jbPhone = $("#jbPhone").val();
    	var jbPhoneTip = $("#jbPhoneTip").text();
    	if (jbPhone != "") {
    		if(jbPhoneTip == "√ 该手机号码可以注册,输入正确" || jbPhoneTip == "√ 短信验证码已发到您的手机,请查收"){
    			// 产生验证码
    			for ( var i = 0; i < codeLength; i++) {
    				code += parseInt(Math.random() * 9).toString();
    			}
    			// 设置button效果,开始计时
    			$("#btnSendCode").attr("disabled", "true");
    			$("#btnSendCode").val("请在" + curCount + "秒内输入验证码");
    			InterValObj = window.setInterval(SetRemainTime, 1000); // 启动计时器,1秒执行一次
    			// 向后台发送处理数据
    			$.ajax({
    				type: "POST", // 用POST方式传输
    				dataType: "text", // 数据格式:JSON
    				url: "UserAction_sms.action", // 目标地址
    				data: "jbPhone=" + jbPhone +"&code=" + code,
    				error: function (XMLHttpRequest, textStatus, errorThrown) { 
    					
    				},
    				success: function (data){ 
    					data = parseInt(data, 10);
    					if(data == 1){
    						$("#jbPhoneTip").html("<font color='#339933'>√ 短信验证码已发到您的手机,请查收</font>");
    					}else if(data == 0){
    						$("#jbPhoneTip").html("<font color='red'>× 短信验证码发送失败,请重新发送</font>");
    					}else if(data == 2){
    						$("#jbPhoneTip").html("<font color='red'>× 该手机号码今天发送验证码过多</font>");
    					}
    				}
    			});
    		}
    	}else{
    		$("#jbPhoneTip").html("<font color='red'>× 手机号码不能为空</font>");
    	}
    }
    
    //timer处理函数
    function SetRemainTime() {
    	if (curCount == 0) {                
    		window.clearInterval(InterValObj);// 停止计时器
    		$("#btnSendCode").removeAttr("disabled");// 启用按钮
    		$("#btnSendCode").val("重新发送验证码");
    		code = ""; // 清除验证码。如果不清除,过时间后,输入收到的验证码依然有效
    	}else {
    		curCount--;
    		$("#btnSendCode").val("请在" + curCount + "秒内输入验证码");
    	}
    }
    
    $(document).ready(function() {
    	$("#SmsCheckCode").blur(function() {
    		var SmsCheckCodeVal = $("#SmsCheckCode").val();
    		// 向后台发送处理数据
    		$.ajax({
    			url : "UserAction_checkCode.action", 
    			data : {SmsCheckCode : SmsCheckCodeVal}, 
    			type : "POST", 
    			dataType : "text", 
    			success : function(data) {
    				data = parseInt(data, 10);
    				if (data == 1) {
    					$("#SmsCheckCodeTip").html("<font color='#339933'>√ 短信验证码正确,请继续</font>");
    				} else {
    					$("#SmsCheckCodeTip").html("<font color='red'>× 短信验证码有误,请核实后重新填写</font>");
    				}
    			}
    		});
    	});
    });

     

    四:验证码用户名和手机号码的js:register.js

     

    //去掉前后空格
    function trim(str) {
    	var strnew = str.replace(/^\s*|\s*$/g, "");
    	return strnew;
    }
    //用户名
    function checkusername() {
    	var username = document.form1.username.value;
    	if (username == "" || !isNaN(username.charAt(0))) {
    		document.getElementById("usernameTip").innerHTML = "<font color='red'>× 首字母不能为数字或者用户名不能为空</font>";
    		return false;
    	} else if (username.length < 6 || username.length > 30) {
    		document.getElementById("usernameTip").innerHTML = "<font color='red'>× 用户名长度为6-30位字符</font>";
    		return false;
    	} else {
    		document.getElementById("usernameTip").innerHTML = "<font color='#339933'>√ 用户名合格</font>";
    		// 向后台发送处理数据
    		$.ajax({
    			url : "UserAction_checkUserName.action",// 目标地址
    			data : {username : username}, // 目标参数
    			type : "POST", // 用POST方式传输
    			dataType : "text", // 数据格式:text
    			success : function(data) {
    				data = parseInt(data, 10);
    				if (data != 0) {
    					$("#usernameTip").html("<font color='red'>× 该用户名已经被注册,请重新输入</font>");
    				} else {
    					$("#usernameTip").html("<font color='#339933'>√ 该用户名可以注册,输入正确</font>");
    				}
    			}
    		});
    		return true;
    	}
    }
    // 登录密码
    function checkpassword() {
    	var password = document.form1.password.value;
    	if (password.length < 6 || password.length > 30) {
    		document.getElementById("passwordTip").innerHTML = "<font color='red'>× 密码长度不能小于6位,大于30位</font>";
    		return false;
    	} else if (!isNaN(password)) {
    		document.getElementById("passwordTip").innerHTML = "<font color='red'>× 密码不能全是数字</font>";
    		return false;
    	} else {
    		document.getElementById("passwordTip").innerHTML = "<font color='#339933'>√ 密码合格</font>";
    		return true;
    	}
    }
    // 确认密码
    function checkpasswrodb() {
    	var password = document.form1.password.value;
    	var passwordRepeat = document.form1.passwordRepeat.value;
    	if (trim(password) != trim(passwordRepeat)) {
    		document.getElementById("passwordRepeatTip").innerHTML = "<font color='red'>× 两次密码输入必须一致</font>";
    		return false;
    	} else {
    		document.getElementById("passwordRepeatTip").innerHTML = "<font color='#339933'>√ 密码输入一致</font>";
    		return true;
    	}
    }
    // 姓名
    function checknickname() {
    	var nickname = document.form1.nickname.value;
    	if (trim(nickname) == "") {
    		document.getElementById("nicknameTip").innerHTML = "<font color='red'>× 姓名不能为空</font>";
    		return false;
    	} else {
    		document.getElementById("nicknameTip").innerHTML = "<font color='#339933'>√ 姓名输入正确</font>";
    		return true;
    	}
    }
    // 联系手机(ajax验证手机号码是否已经存在)
    function checkjbPhone() {
    	var jbPhone = document.form1.jbPhone.value;
    	var re= /(^1[3|5|8][0-9]{9}$)/;
    	if (trim(jbPhone) == "") {
    		document.getElementById("jbPhoneTip").innerHTML = "<font color='red'>× 手机号码不能为空</font>";
    		return false;
    	} else if(trim(jbPhone) != ""){
    		if(!re.test(jbPhone)){
    			document.getElementById("jbPhoneTip").innerHTML = "<font color='red'>× 请输入有效的手机号码</font>";
    			return false;
    		}else{
    			document.getElementById("jbPhoneTip").innerHTML = "<font color='#339933'>√ 手机号码输入正确</font>";
    			// 向后台发送处理数据
    			$.ajax({
    				url : "UserAction_checkPhone.action",// 目标地址
    				data : {jbPhone : jbPhone}, // 目标参数
    				type : "POST", // 用POST方式传输
    				dataType : "text", // 数据格式:text
    				success : function(data) {
    					data = parseInt(data, 10);
    					if (data != 0) {
    						$("#jbPhoneTip").html("<font color='red'>× 该手机号码已经被注册,请重新输入</font>");
    					} else {
    						$("#jbPhoneTip").html("<font color='#339933'>√ 该手机号码可以注册,输入正确</font>");
    					}
    				}
    			});
    			return true;
    		}
    	}
    	
    }
    // 证件号码
    function checkjbCredentialsCode() {
        var jbCredentialsCode = document.form1.jbCredentialsCode.value;
        var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/; 
    	if (trim(jbCredentialsCode) == "") {
    		document.getElementById("jbCredentialsCodeTip").innerHTML = "<font color='red'>× 证件号码不能为空</font>";
    		return false;
    	} else if(trim(jbCredentialsCode) != ""){
    		if(!reg.test(jbCredentialsCode)){
    			document.getElementById("jbCredentialsCodeTip").innerHTML = "<font color='red'>× 请输入合法的证件号码</font>";
    			return false;
    		}else{
    			document.getElementById("jbCredentialsCodeTip").innerHTML = "<font color='#339933'>√ 证件号码输入正确</font>";
    			// 向后台发送处理数据
    			$.ajax({
    				url : "UserAction_checkCredentialsCode.action",// 目标地址
    				data : {jbCredentialsCode : jbCredentialsCode}, // 目标参数
    				type : "POST", // 用POST方式传输
    				dataType : "text", // 数据格式:text
    				success : function(data) {
    					data = parseInt(data, 10);
    					if (data != 0) {
    						$("#jbCredentialsCodeTip").html("<font color='red'>× 该证件号码已经被注册,请重新输入</font>");
    					} else {
    						$("#jbCredentialsCodeTip").html("<font color='#339933'>√ 该证件号码可以注册,输入正确</font>");
    					}
    				}
    			});
    			return true;
    		}
    	}
    }
    // 所在地区
    function checkjbSourceArea() {
    	var jbSourceArea = document.form1.jbSourceArea.value;
    	if (trim(jbSourceArea) == "") {
    		document.getElementById("jbSourceAreaTip").innerHTML = "<font color='red'>× 请选择所在地区</font>";
    		return false;
    	} else {
    		document.getElementById("jbSourceAreaTip").innerHTML = "<font color='#339933'>√ 所在地区选择正确</font>";
    		return true;
    	}
    }
    // 验证码
    function checkNumber() {
    	var checkNum = document.form1.checkNum.value;
    	if (trim(checkNum) == "") {
    		document.getElementById("checkNumTip").innerHTML = "<font color='red'>× 验证码不能为空</font>";
    		return false;
    	} else {
    		document.getElementById("checkNumTip").innerHTML = "<font color='#339933'>√ 验证码合格</font>";
    		// 向后台发送处理数据
    		$.ajax({
    			url : "UserAction_checkNum.action",// 目标地址
    			data : {checkNum : checkNum}, // 目标参数
    			type : "POST", // 用POST方式传输
    			dataType : "text", // 数据格式:text
    			success : function(data) {
    				data = parseInt(data, 10);
    				if (data != 0) {
    					$("#checkNumTip").html("<font color='red'>× 验证码错误</font>");
    				} else {
    					$("#checkNumTip").html("<font color='#339933'>√ 验证码正确</font>");
    				}
    			}
    		});
    		return true;
    	}
    }

     

     

    五:后台action的代码:UserAction.java(这里只是调用了我们的第三方给提供的客户端代码的发送短信的方法,如果是调用其他的短信平台,可以换成他们的发送短信的方法,这里只是给大家做个参考)

     

     

    package cn.gov.csrc.base.systemmanager.action;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.List;
    
    import javax.annotation.Resource;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.log4j.Logger;
    import org.apache.struts2.convention.annotation.Action;
    import org.apache.struts2.convention.annotation.Result;
    import org.apache.struts2.convention.annotation.Results;
    import org.springframework.context.annotation.Scope;
    import org.springframework.security.authentication.encoding.MessageDigestPasswordEncoder;
    import org.springframework.security.core.context.SecurityContextHolder;
    import org.springframework.stereotype.Controller;
    
    import cn.gov.csrc.base.action.BaseAction;
    import cn.gov.csrc.base.log.service.LogService;
    import cn.gov.csrc.base.report.util.CommonUtil;
    import cn.gov.csrc.base.report.util.Env;
    import cn.gov.csrc.base.systemmanager.model.Count;
    import cn.gov.csrc.base.systemmanager.model.User;
    import cn.gov.csrc.base.systemmanager.service.CountService;
    import cn.gov.csrc.base.systemmanager.service.UserService;
    import cn.gov.csrc.base.util.WebContextUtil;
    
    import com.sms.webservice.client.SmsReturnObj;
    import com.sms.webservice.client.SmsWebClient;
    /**
     * File: UserAction.java 
     * Author: jiangsai 
     * Version: 1.1 
     * Date: 04/17/2013 
     * Modify:
     * Description:用户 
     * Copyright csrc
     */
    @Controller()
    @Scope("prototype")
    @Results({
    		@Result(name = "success", location = "/statics/report.jsp"),
    		@Result(name = "modifyPassword", location = "/statics/modifyPassword.jsp")
    		})
    public class UserAction extends BaseAction<User> {
    	
    	private static final long serialVersionUID = 1214696686677691191L;
    	private static Logger log = Logger.getLogger(UserAction.class);
    	private static final String url = Env.getInstance().getProperty("url");
    	private static final String userName = Env.getInstance().getProperty(
    			"username");
    	private static final String passWord = Env.getInstance().getProperty(
    			"password");
    
    	private Integer id;
    
    	private String username;// 用户名
    
    	private String password;// 密码
    
    	private String passwordRepeat;// 确认密码
    	
    	private String jbPhone;//手机号码
    	
    	private String jbCredentialsCode;//身份证号码
    	
    	private String checkNum;//图片验证码
    
    	private String newPassword;
    
    	private String confirmPassword;
    
    	private Integer[] ownRoleIds;
    
    	private UserService userService;
    	
    	private CountService countService;
    	
    	private LogService logService;
    	
    	private Count count = new Count();
    
    	public Integer getId() {
    		return id;
    	}
    
    	public void setId(Integer id) {
    		this.id = id;
    	}
    
    	public String getUsername() {
    		return username;
    	}
    
    	public void setUsername(String username) {
    		this.username = username;
    	}
    
    	public String getPassword() {
    		return password;
    	}
    
    	public void setPassword(String password) {
    		this.password = password;
    	}
    
    	public String getPasswordRepeat() {
    		return passwordRepeat;
    	}
    
    	public void setPasswordRepeat(String passwordRepeat) {
    		this.passwordRepeat = passwordRepeat;
    	}
    	
    	public String getJbPhone() {
    		return jbPhone;
    	}
    
    	public void setJbPhone(String jbPhone) {
    		this.jbPhone = jbPhone;
    	}
    	
    	public String getJbCredentialsCode() {
    		return jbCredentialsCode;
    	}
    
    	public void setJbCredentialsCode(String jbCredentialsCode) {
    		this.jbCredentialsCode = jbCredentialsCode;
    	}
    
    	public String getCheckNum() {
    		return checkNum;
    	}
    
    	public void setCheckNum(String checkNum) {
    		this.checkNum = checkNum;
    	}
    
    	public Integer[] getOwnRoleIds() {
    		return ownRoleIds;
    	}
    
    	public void setOwnRoleIds(Integer[] ownRoleIds) {
    		this.ownRoleIds = ownRoleIds;
    	}
    
    	public String getNewPassword() {
    		return newPassword;
    	}
    
    	public void setNewPassword(String newPassword) {
    		this.newPassword = newPassword;
    	}
    
    	public String getConfirmPassword() {
    		return confirmPassword;
    	}
    
    	public void setConfirmPassword(String confirmPassword) {
    		this.confirmPassword = confirmPassword;
    	}
    
    	@Resource
    	public void setUserService(UserService userService) {
    		this.userService = userService;
    	}
    
    	public UserService getUserService() {
    		return userService;
    	}
    
    	@Resource
    	public void setCountService(CountService countService) {
    		this.countService = countService;
    	}
    
    	public CountService getCountService() {
    		return countService;
    	}
    	
    	public LogService getLogService() {
    		return logService;
    	}
    
    	@Resource
    	public void setLogService(LogService logService) {
    		this.logService = logService;
    	}
    
    	public Count getCount() {
    		return count;
    	}
    
    	public void setCount(Count count) {
    		this.count = count;
    	}
    
    	public void prepareToUpdatePage() {
    		model = userService.getEntity(id);
    	}
    	
    	/**
    	 * 用户登录
    	 * 
    	 * @return success
    	 */
    	@Action(value = "UserAction_login")
    	public String login() {
    		Object u = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    		if (u instanceof User && u != null) {
    			WebContextUtil.getSession().setAttribute("user", u);
    			User user = (User)u;
    			//使用数据库表TBL_BASE_LOG添加用户登录的日志信息
    			logService.saveTblBaseLog(WebContextUtil.getRequest(),"当前操作人【"+user.getNickname()+"】登录系统");
    		} else {
    			// 防止绕过登陆页面直接执行Action
    			return "login";
    		}
    		return SUCCESS;
    	}
    	
    	/**
    	 * 用户密码更新
    	 */
    	@Action(value = "UserAction_updateUser")
    	public String updateUser() {
    		if (!newPassword.equals(confirmPassword)) {
    			this.setMessage("新密码与确认密码不一致!");
    			return "modifyPassword";
    		}
    		User u = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    		MessageDigestPasswordEncoder encoder = new MessageDigestPasswordEncoder("md5");
    		String psw = encoder.encodePassword(newPassword, null);
    		userService.modifyPassword(u, psw);
    		this.setMessage("保存成功!");
    		return "modifyPassword";
    	}
    	
    	/**
    	 * 验证用户名是否存在
    	 * 
    	 * @throws Exception
    	 */
    	@Action(value = "UserAction_checkUserName")
    	public void checkUserName(){
    		String result = "0";
    		try {
    			List<User> list = userService.findUserByUserName(username);
    			if(list != null && list.size() > 0){
    				result = "1";
    			}else{
    				result = "0";
    			}
    			HttpServletResponse response = WebContextUtil.getResponse();
    			response.setContentType("application/json;charset=UTF-8");
    			response.setHeader("Cache-Control", "no-cache");
    			PrintWriter out = response.getWriter();
    			out.write(result.toString());
    		} catch (IOException e) {
    			throw new RuntimeException("验证身份证号码出错", e);
    		}
    	}
    
    	/**
    	 * 验证原始密码是否正确
    	 * 
    	 * @throws Exception
    	 */
    	@Action(value = "UserAction_checkPassWord")
    	public void checkPassWord() throws Exception {
    		String result = "0";
    		MessageDigestPasswordEncoder encoder = new MessageDigestPasswordEncoder("md5");
    		String pwd = encoder.encodePassword(password, null);
    		List<User> user = userService.findUserByPassWord(pwd);
    		if (user != null && user.size() > 0) {
    			result = "1";
    		}else{
    			result = "0";
    		}
    		HttpServletResponse response = WebContextUtil.getResponse();
    		response.setContentType("application/json;charset=UTF-8");
    		response.setHeader("Cache-Control", "no-cache");
    		PrintWriter out = response.getWriter();
    		out.write(result.toString());
    	}
    	
    	/**
    	 * 验证手机号码是否存在
    	 */
    	@Action(value = "UserAction_checkPhone")
    	public void checkPhone(){
    		String result = "0";
    		try {
    			List<User> list = userService.findUserByPhone(jbPhone);
    			if(list != null && list.size() > 0){
    				result = "1";
    			}else{
    				result = "0";
    			}
    			HttpServletResponse response = WebContextUtil.getResponse();
    			response.setContentType("application/json;charset=UTF-8");
    			response.setHeader("Cache-Control", "no-cache");
    			PrintWriter out = response.getWriter();
    			out.write(result.toString());
    		} catch (IOException e) {
    			throw new RuntimeException("验证手机号码出错", e);
    		}
    	}
    	
    	/**
    	 * 验证身份证号码是否存在
    	 */
    	@Action(value = "UserAction_checkCredentialsCode")
    	public void checkCredentialsCode(){
    		String result = "0";
    		try {
    			List<User> list = userService.findUserByCredentialsCode(jbCredentialsCode);
    			if(list != null && list.size() > 0){
    				result = "1";
    			}else{
    				result = "0";
    			}
    			HttpServletResponse response = WebContextUtil.getResponse();
    			response.setContentType("application/json;charset=UTF-8");
    			response.setHeader("Cache-Control", "no-cache");
    			PrintWriter out = response.getWriter();
    			out.write(result.toString());
    		} catch (IOException e) {
    			throw new RuntimeException("验证身份证号码出错", e);
    		}
    	}
    	
    	/**
    	 * 验证验证码是否正确
    	 */
    	@Action(value = "UserAction_checkNum")
    	public void checkNum(){
    		try {
    			String result = "0";
    			String check_number_key = (String)WebContextUtil.getSession().getAttribute("CHECK_NUMBER_KEY");
    			if(checkNum != check_number_key && !checkNum.equals(check_number_key)){
    				result = "1";
    			}else{
    				result = "0";
    			}
    			HttpServletResponse response = WebContextUtil.getResponse();
    			response.setContentType("application/json;charset=UTF-8");
    			response.setHeader("Cache-Control", "no-cache");
    			PrintWriter out = response.getWriter();
    			out.write(result.toString());
    		} catch (IOException e) {
    			throw new RuntimeException("验证验证码出错", e);
    		}
    	}
    	
    	/**
    	 * 验证短信验证码是否正确
    	 * 
    	 * @throws Exception
    	 */
    	@Action(value = "UserAction_checkCode")
    	public void checkCode() throws Exception{
    		String result = "0";
    		/** 获取手动输入的手机短信验证码 */
    		String SmsCheckCode = WebContextUtil.getRequest().getParameter("SmsCheckCode");
    		/** 获取session中存放的手机短信验证码 */
    		String code = (String) WebContextUtil.getSession().getAttribute("code");
    		try {
    			if(SmsCheckCode != code && !SmsCheckCode.equals(code)){
    				result = "0";
    			}else{
    				result = "1";
    			}
    		} catch (Exception e) {
    			throw new RuntimeException("短信验证失败", e);
    		}
    		HttpServletResponse response = WebContextUtil.getResponse();
    		response.setContentType("application/json;charset=UTF-8");
    		response.setHeader("Cache-Control", "no-cache");
    		PrintWriter out = response.getWriter();
    		out.write(result.toString());
    	}
    	
    	/**
    	 * 验证手机短信是否发送成功
    	 * 
    	 * @throws Exception
    	 */
    	@Action(value = "UserAction_sms")
    	public void sms() throws Exception {
    		String result = "0";
    		/** 手机号码 */
    		String jbPhone = WebContextUtil.getRequest().getParameter("jbPhone");
    		/** 短信验证码 */
    		String code = WebContextUtil.getRequest().getParameter("code");
    		/** 短信验证码存入session(session的默认失效时间30分钟) */
    		WebContextUtil.getSession().setAttribute("code", code);
    		/** 如何初始化失败返回 */
    		if(!initClient()) {
    			return;
    		}
    		/** 单个手机号发送短信的方法的参数准备 */
    		// 手机号码
    		String mobilephone = jbPhone;
    		// 短信内容+随机生成的6位短信验证码
    		String content = "根据中国证监会举报中心委托,特向您发送此条短信。您的注册验证码为:" + code;
    		// 操作用户的ID
    		Integer operId = Integer.parseInt(Env.getInstance().getProperty("operId"));
    		// 定时发送的的发送时间(缺省为空,如果即时发送,填空)
    		String tosend_time = "";
    		// 应用系统的短信ID,用户查询该短信的状态报告(缺省为0,即不需查询短信的状态报告)
    		int sms_id = 0;
    		// 黑名单过滤(0:不需要黑名单过滤,1:需要黑名单过滤,缺省为0)
    		short backlist_filter = 0;
    		// 禁止语过滤(0:不需要禁止语过滤,1:需要禁止语过滤,缺省为0)
    		short fbdword_filter = 0;
    		// 优先级(值越大优先级越高,0:普通,1,:优先,2:最高,缺省为0)
    		short priority = 0;
    		// 短信有效时间(格式为:YYYY-MM-DD HH:mm:ss目前为空)
    		String valid_time = "";
    		/** 发送短信之前先统计一个已经发送的短信条数 */
    		int messageCount = countService.findAllRecord(mobilephone);
    		log.info("已发短信条数为:" +messageCount);
    		if(messageCount < 5){
    			/** 单个手机号发送短信 */
    			if (!sendMessage(mobilephone, content, operId, tosend_time, sms_id,
    					backlist_filter, fbdword_filter, priority, valid_time)) {
    				result = "0";// 失败
    			} else {
    				result = "1";// 成功
    				/** 发送一条短信,记录一条短信记录,为了方便之后的统计短信发送次数 */
    				count.setPhone(mobilephone);// 手机号码
    				count.setCaptcha(code);// 短信验证码
    				count.setSendTime(CommonUtil.getNowDate());// 短信发送时间
    				if(count != null){
    					countService.saveEntity(count);
    					log.info("短信验证码发送记录保存成功!");
    				}
    			}
    		}else{
    			result = "2";//一个手机号码最多发送5条短信验证码
    			log.info("该手机号码今天发送验证码过多");
    		}
    		HttpServletResponse response = WebContextUtil.getResponse();
    		response.setContentType("application/json;charset=UTF-8");
    		response.setHeader("Cache-Control", "no-cache");
    		PrintWriter out = response.getWriter();
    		out.write(result.toString());
    	}
    	
    	/**
    	 * WebService客户端初始化
    	 * 
    	 */
    	public static boolean initClient() {
    		/**
    		 * 判断客户端是否已经初始化
    		 */
    		if (!SmsWebClient.enable()) {
    			int ret = 0;
    			try {
    				ret = SmsWebClient.init(url, userName, passWord);
    				if (ret == -1 || !SmsWebClient.enable()) {
    					log.info("短信平台接口初始化失败!");
    					return false;
    				}
    				log.info("短信平台接口初始化成功!" + ret + "-----");
    			} catch (Exception ex) {
    				ex.printStackTrace();
    				log.info("短信平台接口初始化过程中异常!");
    			}
    		}
    		return true;
    	}
    	
    	/**
    	 * 单个手机号码发送
    	 * 
    	 * @param mobilephone
    	 *            手机号
    	 * @param content
    	 *            短信内容
    	 * @param operId
    	 *            操作用户的ID
    	 * @param tosend_time
    	 *            定时发送的发送时间
    	 * @param sms_id
    	 *            应用系统的短信ID
    	 * @param backlist_filter
    	 *            黑名单过滤
    	 * @param fbdword_filter
    	 *            禁止语过滤
    	 * @param priority
    	 *            优先级
    	 * @param valid_time
    	 *            短信有效时间
    	 */
    	public static boolean sendMessage(java.lang.String mobilephone,
    			java.lang.String content, int operId, java.lang.String tosend_time,
    			int sms_id, short backlist_filter, short fbdword_filter,
    			short priority, java.lang.String valid_time) {
    		// 单个手机号码发送
    		try {
    			SmsReturnObj retObj = SmsWebClient.webSendMessage(mobilephone,
    					content, operId, tosend_time, sms_id, backlist_filter,
    					fbdword_filter, priority, valid_time);
    			if (retObj.getReturnCode() != 1) {
    				log.info("短信发送失败,原因为:" + retObj.getReturnMsg());
    				return false;
    			} else {
    				log.info("短信发送成功!返回结果为:" + retObj.getReturnMsg());
    				return true;
    			}
    		} catch (Exception ex) {
    			ex.printStackTrace();
    			log.info("短信发送过程发生异常!");
    		}
    		return true;
    	}
    	
    	
    }
    

     

     

     

     

     

    六:具体的短信接口demo到这里下,这里你下载了也不能成功的发送短信,因为你必须要短信平台商给你提供:url,userName,passWord,operId,以及短信平台商还要绑定你的外网ip地址,这样才能真正的发送短信。

    Demo下载链接: http://pan.baidu.com/s/1qWt1Qdm

     

    原文:http://www.zuidaima.com/share/1881657001233408.htm

    七:最后,如果有小伙伴在学习的过程中有问题,可以添加楼主微信,楼主会尽量抽时间帮你解决遇到的问题;

    八:如果还是没解决,可以加入QQ交流群讨论解决:

     

    展开全文
  • webService接口调用

    2019-10-16 16:26:32
    调用webService接口: /* * WebServiceUtil * * 2015年11月6日 * * (C) Copyright 2015 Suzhou USTC Sinovate Information Technology Co., Ltd. (http://www.ustcinfo.com/index.shtml). * * All rights ...

    调用webService接口:

    /*
     * WebServiceUtil
     *
     * 2015年11月6日
     * 
     * (C) Copyright 2015 Suzhou USTC Sinovate Information Technology Co., Ltd. (http://www.ustcinfo.com/index.shtml).
     *
     * All rights reserved.
     */
    
    package com.ustcinfo.eoms.portal.util;
    
    import java.net.HttpURLConnection;
    import java.net.URL;
    
    import net.sf.json.JSONSerializer;
    import net.sf.json.xml.XMLSerializer;
    
    import org.apache.log4j.Logger;
    import org.codehaus.xfire.client.Client;
    import org.codehaus.xfire.transport.http.CommonsHttpMessageSender;
    
    /**
     * 
     * <p>WebService客户端 ,用于调用WebService接口
     *
     * @author QKX
     * @version %I%, %G%
     * @since 1.0.0
     * @see
     */
    
    public class WebServiceUtil {
    
    	/**
    	 * 日志.
    	 */
    	private static Logger logger = Logger.getLogger(WebServiceUtil.class);
    	
    	public String wsdlUrl ;
    	public String method;
    	public String[] params;
    	
    	/**
    	 * 
    	 * <p>获取客户端Client
    	 *
    	 * @param wsdlUrl wsdl文件地址 如测试环境:http://192.168.20.23:8001/EOMSZKInterface/services/EmosZkInterface
    	 * @return WebService客户端Client
    	 */
    	public static Client getWebServiceClient(String wsdlUrl){
    		try {
    			//============设置调用接口超时时长============开始
    			int timeout = Integer.parseInt(ConfigUtil.getValue("invokeTimeout")); //从配置文件中读取超时时长
    			
    			URL url = new URL(wsdlUrl);
    			HttpURLConnection httpConnection = (HttpURLConnection)url.openConnection();
    			httpConnection.setReadTimeout(timeout); //设置http连接的读超时,单位是毫秒,等待服务端返回数据的等待时间
    			httpConnection.connect();
    			
    			Client client = new Client(httpConnection.getInputStream(), null);
    			client.setProperty(CommonsHttpMessageSender.HTTP_TIMEOUT, String.valueOf(timeout)); //设置发送的超时限制,单位是毫秒;客户端发送请求的等待时间
    			client.setProperty(CommonsHttpMessageSender.DISABLE_KEEP_ALIVE, "true");
    			client.setProperty(CommonsHttpMessageSender.DISABLE_EXPECT_CONTINUE, "true");
    			
                //============设置调用接口超时时长============结束
    //			Client client = new Client(new URL(wsdlUrl));
    			return client;
    		} catch (Exception e) {
    			logger.info("getWebServiceClient异常,信息:"+e.getMessage());
    		}
    		return null;
    	}
    	
    	/**
    	 * 
    	 * <p> 调用Webservice接口
    	 *
    	 * @param wsdlUrl	接口发布地址(wsdl地址,测试环境:http://192.168.20.23:8001/EOMSZKInterface/services/EmosZkInterface)
    	 * @param method	接口名称:如登录接口(zk_login)
    	 * @param params	接口参数,字符串数组,如登录接口 new String[]{"<?xml version=\"1.0\" encoding=\"utf-8\"?><InputInfo><EOSOperator><userID>sysadmin</userID><password>000000</password></EOSOperator></InputInfo>"}
    	 * @return	接口调用结果
    	 */
    	public static String callWebService(String wsdlUrl, String method, String[] params){
    		Client client = null;
    		try {
    			client = getWebServiceClient(wsdlUrl);
    			logger.info("调用接口开始,地址:"+wsdlUrl+"\n请求报文:"+params[0]);
    			Object[] result = client.invoke(method,params);
    			logger.info("调用接口结束,地址:"+wsdlUrl+"\n返回报文:"+result[0].toString());
    			client.close();
    			if(result != null && result.length>0) {
    				return result[0].toString();
    			}
    		} catch (Exception e) {
    			logger.info("callWebService1调用接口异常,信息:"+e.getMessage()+"\n地址:"+wsdlUrl+"\n请求报文:"+params[0]);
    		} finally{
    			if(client != null) {
    				client.close();
    				client = null;
    			}
    		}
    		
    		return "{'errorMsg','WebService server exception.'}";
    	}
    	
    	
    	/**
    	 * 
    	 * <p> 调用Webservice接口
    	 *
    	 * @param wsdlUrl	接口发布地址(wsdl地址,测试环境:http://192.168.20.23:8001/EOMSZKInterface/services/EmosZkInterface)
    	 * @param method	接口名称:如登录接口(zk_login)
    	 * @param param		请求报文:字符串
    	 * @return	接口调用结果
    	 */
    	public static String callWebService(String wsdlUrl, String method, String param){
    //		Client client = null;
    //		try {
    //			client = getWebServiceClient(wsdlUrl);
    //			logger.info("callWebService2调用接口开始,地址:"+wsdlUrl+"\n请求报文:"+param);
    //			Object[] result = client.invoke(method,new String[]{param});
    //			client.close();
    //			if(result != null && result.length>0) {
    //				return result[0].toString();
    //			}
    //		} catch (Exception e) {
    //			logger.info("callWebService2调用接口异常,信息:"+e.getMessage()+"\n地址:"+wsdlUrl+"\n请求报文:"+param);
    //		} finally{
    //			if(client != null) {
    //				client.close();
    //				client = null;
    //			}
    //		}
    		
    		return callWebService(wsdlUrl, method, new String[]{param});
    	}
    	
    	/**
    	 * 
    	 * <p>将返回的xml转换为json字符串
    	 *
    	 * @param xmlParam
    	 * @return
    	 */
    	public static String parseXml2Json(String xmlParam){
    		XMLSerializer xmlSerializer = new XMLSerializer();
    		String jsonStr = xmlSerializer.read(xmlParam).toString();
    		
    		return jsonStr;
    	}
    	
    	/**
    	 * 
    	 * <p>将json格式字符串转换为xml
    	 *
    	 * @param jsonParam
    	 * @return
    	 */
    	public static String parseJson2Xml(String jsonParam){
    		XMLSerializer xmlSerializer = new XMLSerializer();
    		xmlSerializer.setRootName("OutputInfo");
    		xmlSerializer.setArrayName("userList");
    		xmlSerializer.setElementName("entity");
    		xmlSerializer.setNamespaceLenient(false);
    		String xmlStr = xmlSerializer.write((JSONSerializer.toJSON(jsonParam)),"UTF-8");
    		return xmlStr;
    	}
    	
    //	/**
    //	 * 
    //	 * <p>通过map生成接口的入参报文:<InputInfo> ... </InputInfo>
    //	 *
    //	 * @param paramsMap
    //	 * @return
    //	 */
    	// 未被使用 -- 2016-3-20 liuqian
    //	public static String getInputXML(Map<String, String> paramsMap) {
    //		try {
    //		
    //			DocumentBuilderFactory docBuilder = DocumentBuilderFactory.newInstance();
    //			DocumentBuilder documentBuilder = docBuilder.newDocumentBuilder();
    //			Document document = documentBuilder.newDocument();
    //			Element rootElement = document.createElement("InputInfo");
    //			addNodes(paramsMap,document,rootElement);
    //		} catch (ParserConfigurationException e) {
    //			e.printStackTrace();
    //		}
    //		
    //		if(paramsMap != null) {
    //			//map不为空:
    //		}
    //		
    //		return null;
    //	}
         
    //	/**
    //	 * 
    //	 * <p>根据map生产document
    //	 *
    //	 * @param paramsMap 数据源
    //	 * @param document 根元素
    //	 * @param rootElement 父级标签
    //	 */
    	// 未被使用 -- 2016-3-20 liuqian
    //	private static void addNodes(Map<String, String> paramsMap,
    //			Document document, Element element) {
    //		Set<String> keys = paramsMap.keySet();
    //		for(Iterator<String> it = keys.iterator();it.hasNext();){
    //			String key = it.next();
    //			if(key.contains("/")){
    //				String[] keyArr = key.split("/");
    //				Element childElement = document.createElement(keyArr[0]);
    //				//xml中是否含有同名 父级元素
    //				NodeList hasResolve = element.getElementsByTagName(keyArr[0]);
    //			}
    //		}
    //	}
    		
    }
    

     

    展开全文
  • Webservice 接口调用

    千次阅读 2018-08-07 18:07:25
    最近项目中频繁遇到web service接口调用,调用起来有点麻烦,若使用wsimport命令生成客户端的方式调用,容易造成项目代码臃肿,简单整理了个ws调用工具,方便在项目开发中使用。 WebServiceUtil import java....
  • webservice 接口调用

    2016-12-09 14:09:11
    今天修复了一个接口调用不通的BUG,代码贴上来供后来者参考`Object result = null; Service service = null; Call call = null; try { service = new Service(); call = (Call) ser
  • webservice接口调用实例

    2017-08-10 17:51:36
    webservice接口调用实例,经个人验证可用
  • webservice接口调用jar包

    2018-11-13 14:53:48
    webservice接口调用需要使用的jar包汇总。
  • Java对于webservice接口调用以及xml数据类型转json解析webservice接口调用cxf Mavenwebservice接口调用案例xml转json所需Mavenxml转json案例 webservice接口调用 调用webservice接口本文使用的是cxf cxf Maven <...
  • <artifactId>cxf-rt-transports-httpartifactId> <version>3.4.0version> dependency> 四、调用实例 public static void main(String args[]) throws Exception { URL wsdlURL = WebService2020.WSDL_LOCATION;...
  • 本C#实例主要为和我一样的初学者理解时钟控件timer和webservice接口调用的学习编写的实例,希望对小白们有所帮助。学习之路是痛苦的,痛苦之后是成就感。
  • c# winform 调用公共天气预报webservice接口,初学者参考,大神忽略 c# winform 调用公共天气预报webservice接口,初学者参考,大神忽略
  • webservice 接口调用Demo

    2016-05-28 15:39:25
    Android webservice demo
  • 用cxf方法调用webService接口和jar包,jdk版本必须大于1.6.
  • webservice 接口调用,soap报文发送 invalid space white 主要是 在这个地方出了问题,wsnr这个字段需要放一个pdf文档内容,我在读取文档内容后,拼写报文时报 invalid space white 错误,网上说是有特殊字符。看...
  • Python webservice 接口调用

    千次阅读 2018-05-13 19:05:27
    python 2接口调用方式python 3接口调用方式import urllib.request, urllib.parse
  • 通过接口url查是哪个服务,以及WebService接口调用soapui使用 接口文档: url: http://137.32.126.168:8080/services/addCard?wsdl(测试环境) 通过上面的url:http://137.32.126.168:8080/services/addCard?wsdl...
  • xfire webservice接口调用

    2017-09-22 15:54:32
    xfire创建webservice调用 xfire生成客户端 把对方的文件打包成一个jar包,引用到本地,通过第一个连接案例就可 以调用发布的接口了。 Service service = new ObjectServiceFactory().create(weaver.mobile.web...
  • 最近在在调用webservice接口,对方的协议是https、自然也就出现了安全证书的问题: Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath....

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 5,799
精华内容 2,319
关键字:

webservice接口调用