java 实现WebService接口调用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/liangzi_lucky/article/details/52118958
	/**
	 * 用户角色查询对外接口
	 * @param accountid 当前用户工号
	 * @param  type 查询类型 type=1  查询用户在CMS的角色 
	 * @param  branchName 分支名称 type为 2 时 必填,其它非必填
	 * @return 返回加密结果xml报文
	 */
	public String queryAccountPermission(String accountid, String type,
			String branchName) {
		log.info("接收参数   WebAccountQuery queryAccountPermissio");
		log.info(" accountid="+accountid+" 	type="+type+"   branchName="+branchName);
		log.info("end=");
		try {
		String result ="";
		String message = "";
		//检测必填项参数是否为空
		if(accountid == null || "".equals(accountid) || type == null || "".equals(type)){
			 result= CMSConstant.ONE ;
			 message=parameterError;
			return sendReturn(result,message,null,accountid);
		}
		if(!CMSConstant.ONE.equals(type) && (branchName == null || "".equals(branchName))){
			 result=CMSConstant.ONE;
			 message=parameterError;
			return sendReturn(result,message,null,accountid);
		}
		//验证用户所传工号是否有效
		Account account = accountService.queryAccount(accountid);
		if(null == account ){
			 result=CMSConstant.ONE;
			 message=noAccount;
			return sendReturn(result,message,null,accountid);
		}
		StringBuffer subject = new StringBuffer();
		// type 等于 1 时 查询该用户 在CMS的角色
		if(CMSConstant.ONE.equals(type)){
			List<CMRole> roleList = roleService.queryAccountRoleList(accountid);
			if(roleList.size() > 0 ){
				 result = CMSConstant.ZERO;
				 message = success;
				subject.append(accountStr+accountid+accountStrs);
				subject.append(permissionStr);
				for (CMRole cmRole : roleList) {
					subject.append("<cmsPermission>"+cmRole.getName()+"</cmsPermission>");
				}
				subject.append(permissionStrs);
			}else {
				 result=CMSConstant.ONE;
				 message="该用户在配置管理系统暂未分配角色";
			}
		}
		<pre name="code" class="java"><span style="white-space:pre">	</span>/**
	 * 封装返回值
	 * @param accountid 用户工号
	 * @param message 返回描述
	 * @param result 返回码
	 * @param subject 返回报文
	 * @return 返回值
	 */
	public String sendReturn(String result,String message,StringBuffer subject ,String accountid){
		return CommonUtil.createXML( result,  message,  subject,accountid);
	}
// 判断返回值是否为空if(null == subject || "".equals(result)){ result=CMSConstant.ONE; message="无返回, 请检查您的参数";}//进行返回String data = CommonUtil.createXML( result, message, subject,accountid);return data;} catch (Exception e) {e.printStackTrace();log.error(errorStr+e);return null;}}

 
 
<pre name="code" class="java"><span style="white-space:pre">	</span>/**
	 * 对外接口报文封装,加密
	 * @param result 返回状态
	 * @param message 返回描述
	 * @param subject 返回内容报文
	 * @param accountid 工号
	 * @return 返回加密后报文
	 */
	public static String createXML(String result,String message,StringBuffer subject,String accountid){
		StringBuffer sb = new StringBuffer();
		sb.append("<xml version='1.0' encoding='UTF-8'>");
		sb.append("<root>");
		sb.append("<resultCode>");
		sb.append(result);
		sb.append("</resultCode>");
		sb.append("<resultMessage>");
		sb.append(message);
		sb.append("</resultMessage>");
		if(null != subject){
			sb.append(subject.toString());
		}
		sb.append("</root>");
		sb.append("</xml>");
		if(null == accountid){
			accountid = "";
		}
		log.info("CMS对外接口   返回报文="+sb.toString());
		String data = DESEncryptionUtil.encrypt(sb.toString(),accountid, "ams_@#$%");//对外接口加密秘钥
		return data;
	}
  /**
     *提供对外加密方法
     * @param data 加密数据
     * @param accountid 用户工号
     * @param key 秘钥
     * @return 字符串
     */
    public static String encrypt(String data,String accountid,String key){
    <span style="white-space:pre">	</span> byte[] enk = hex(accountid,key);
    <span style="white-space:pre">	</span> byte[] encoded = encryptMode(enk,data.getBytes()); 
    <span style="white-space:pre">	</span>return Base64.encode(encoded);
    }
接口调用方法
 
 
<pre name="code" class="java">private  Map<String, String> map;
	private static final String METHODNAME = "methodName";
	private static final String URL = "url";
	private static final String TYPE = "type";
	/**
	 *  调用cms接口传参数
	 *  @return xml 
	 */
	public String query(){	
		try {
             Service service = new Service();
             Call call = (Call) service.createCall();
             call.setTargetEndpointAddress(map.get(URL));
             QName qn = new QName(map.get(METHODNAME));//WSDL里面描述的接口名称
             call.setOperationName(qn);
             call.addParameter(ACCOUNTID, org.apache.axis.encoding.XMLType.XSD_STRING,
                           javax.xml.rpc.ParameterMode.IN);//接口的参数             
             call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);//设置返回类型 
             String result = null;
 if(map.get(TYPE) != null && !"".equals(map.get(TYPE))){
            call.addParameter(TYPE, org.apache.axis.encoding.XMLType.XSD_STRING,
                         javax.xml.rpc.ParameterMode.IN);//接口的参数
            result = (String)call.invoke(new Object[]{map.get(ACCOUNTID),map.get(TYPE)}); 
            }else{
            result = (String)call.invoke(new Object[]{map.get(ACCOUNTID)}); 
             }
             String key = "ams_@#$%";
             result = DESEncryptionUtil.decrypt(result, map.get(ACCOUNTID), key);
             return result;
          } catch (Exception e) {
             System.err.println(e.toString());
             return null;
          }
  /**
     * 提供对外解密方法
     * @param data 
     * @param accountid 工号 
     * @param key 密匙
     * @return String
     * @throws UnsupportedEncodingException  
     */
    public static String decrypt(String data,String accountid,String key) throws UnsupportedEncodingException{
    byte[] enk = hex(accountid,key);
    byte[] dataByte = Base64.decode(data);  
        byte[] srcBytes = decryptMode(enk,dataByte);
    return new String(srcBytes,"UTF-8");
    }
 
 
 /**
     * 
     * @param username 用户名
     * @param key 密匙
     * @return byte[]
     */
    public static byte[] hex(String username,String key){  
        String f = DigestUtils.md5Hex(username+key);  
        byte[] bkeys = new String(f).getBytes();  
        byte[] enk = new byte[24];  
        for (int i=0;i<24;i++){  
            enk[i] = bkeys[i];  
        }  
        return enk;  
    }
/**
     * 
     * @param keybyte 为加密密钥,长度为24字节      
     * @param src 为加密后的缓冲区  
     * @return byte[]
     */
    public static byte[] decryptMode(byte[] keybyte,byte[] src){  
        try {  
            //生成密钥  
            SecretKey deskey = new SecretKeySpec(keybyte, ALGORITHM);  
            //解密  
            Cipher c1 = Cipher.getInstance(ALGORITHM);  
            c1.init(Cipher.DECRYPT_MODE, deskey);  
            return c1.doFinal(src);  
        } catch (java.security.NoSuchAlgorithmException e1) {  
            // TODO: handle exception  
            e1.printStackTrace();  
        }catch(javax.crypto.NoSuchPaddingException e2){  
            e2.printStackTrace();  
        }catch(java.lang.Exception e3){  
            e3.printStackTrace();  
        }  
        return null;          
    }  
<pre name="code" class="java">  /**
     *  查询用户在CMS的角色
     * @param accountId 域账号
     * @param endpoint 接口地址
     * @return 接口返回值xml
     */
	public String queryCMSRole(String accountId,String endpoint){
		map = new HashMap<String, String>();
		map.put(ACCOUNTID, accountId);
		map.put(URL, endpoint);
		map.put(METHODNAME, "queryAccountPermission");
		map.put(TYPE, "1");
		return query();
		
	}
 /**
*  解析xml 查询用户在cms角色
* @param xml 
* @return Set<Account>
*/
public static List<String> getRoleByCMS(String xml){
try {
List<String> roleList = new ArrayList<String>();
Document doc = DocumentHelper.parseText(xml);
Element node = doc.getRootElement(); 
Element root = node.element(ROOT); 
Element resultCode = root.element(CODE); 
if(resultCode.getText().equals(ConstantUtil.ZERO)){//0:成功
Element permissionlist = root.element("permissionList");
List<Element> list= permissionlist.elements("cmsPermission");
for (Element e : list) {
String role = e.getText();
if(role != null && !"".equals(role)){
roleList.add(role);
}
}
}
return roleList;
} catch (Exception e) {
e.printStackTrace();
return null;
}

}


测试对接口调用
 
 
public static void main(String[] args) {
<span style="white-space:pre">		</span>CMSInterface cms = new CMSInterface();
<span style="white-space:pre">		</span>String url = "http://localhost:8080/cms/webservice/foreignService";
<span style="white-space:pre">		</span>String xml = cms.queryCMSRole("123456", url);
<span style="white-space:pre">		</span>List<String> roles = XMLUtil.getRoleByCMS(xml);
}

猜你喜欢

转载自blog.csdn.net/liangzi_lucky/article/details/52118958