webservice学习之客户端封装类

axis1



import java.rmi.RemoteException;

import javax.xml.rpc.ParameterMode;


import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;


public class Axis1ClientUitl {

	public static Object callService(String url,Class type,String method,Object[] args){
		  Call call = initCall(url, method);
		   //执行方法并带上参数
		  Object result=null;
		try {
			result = call.invoke(args);
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		return result;
	}

	private static Call initCall(String url, String method) {
		Service service = new Service();
		Call call = null;
		try {
			call = (Call) service.createCall();
			call.setTargetEndpointAddress(new java.net.URL(url));
			call.setOperationName(new javax.xml.namespace.QName("urn:sap-com:document:sap:soap:functions:mc-style", method));
			call.setReturnClass(org.w3c.dom.Element.class);
			call.addParameter("op1", XMLType.XSD_STRING, ParameterMode.IN);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return call;
	}
}

 

AXIS2

 

import javax.xml.namespace.QName;

import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.rpc.client.RPCServiceClient;
public class Axis2ClientUtil {

	/**
	 * 初始化调用客户端
	 * @return
	 */
	private static RPCServiceClient initServiceClient(String serviceURL){
		 //  使用RPC方式调用WebService        
        RPCServiceClient serviceClient;
		try {
			serviceClient = new RPCServiceClient();
			Options options = serviceClient.getOptions();
			//  指定调用WebService的URL
			EndpointReference targetEPR = new EndpointReference(serviceURL);
			options.setTo(targetEPR);
			return serviceClient;
		} catch (AxisFault e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 调用service
	 * @return
	 */
	public static Object[] callService(String serviceURL,Class type,String methodName,String args){
		
	    try {
	    	RPCServiceClient service2Client = initServiceClient(serviceURL);
	    	//  指定methodName方法的参数值
	    	Object[] opAddEntryArgs = new Object[] {args};
	    	//  指定methodName方法返回值的数据类型的Class对象
	    	Class[] classes = new Class[] {type};
	    	//  指定要调用的methodName方法及WSDL文件的命名空间
	    	QName opAddEntry = new QName("urn:sap-com:document:sap:soap:functions:mc-style", methodName);
			return service2Client.invokeBlocking(opAddEntry, opAddEntryArgs,classes);
		} catch (AxisFault e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    return null;
	}

}


 

 

 

JAVA.NET  URL方式调用

 

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class UrlCallServiceUtil {

        /**
	 * 
	 * @param strURL 要调用的url地址
	 * @param strCharse	设置字符编码方式,为null,设置为utf8
	 * @return
	 * @throws Exception
	 */
	public static String postRequest(String strURL, String strCharset)
			throws Exception {
		if ((strURL == null) || (strURL.length() == 0))
			return null;
		if ((strCharset == null) || (strCharset.length() == 0)) {
			strCharset = "UTF-8";
		}
		String[] arrContent = (String[]) null;
		if (strURL.indexOf("?") > -1) {
			arrContent = string2Array(strURL.substring(strURL.indexOf("?") + 1), '&', false);
			strURL = strURL.substring(0, strURL.indexOf("?"));
		}

		StringBuffer sb = new StringBuffer();
		HttpURLConnection con = null;
		try {
			URL url = new URL(strURL);
			con = (HttpURLConnection) url.openConnection();
			con.setDoOutput(true);
			con.setDoInput(true);
			con.setInstanceFollowRedirects(true);
			con.setRequestMethod("POST");
			con.addRequestProperty("Content-type","application/x-www-form-urlencoded");
			con.setUseCaches(false);
			con.connect();

			if ((arrContent != null) && (arrContent.length > 0)) {
				StringBuffer sbContent = new StringBuffer();
				for (int i = 0; i < arrContent.length; i++) {
					if ((arrContent[i] == null)	|| (arrContent[i].indexOf("=") == -1))
						continue;
					sbContent.append(arrContent[i].substring(0,	arrContent[i].indexOf("="))).append("=");
					sbContent.append(URLEncoder.encode(arrContent[i].substring(arrContent[i].indexOf("=") + 1),strCharset)).append("&");
				}
				DataOutputStream out = new DataOutputStream(con.getOutputStream());
				out.writeBytes(sbContent.toString());
				out.flush();
				out.close();
			}

			BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), strCharset));
			String line;
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
			con.disconnect();
			return sb.toString();
		} catch (Exception e) {
			System.out.print(e.getMessage());
			sb.append(e.getMessage());
			String str1 = sb.toString();
			return str1;
		} finally {
			if (con != null)
				con = null;
		}
	}

	public static String[] string2Array(String s, char delim, boolean trim) {
		if (s.length() == 0)
			return new String[] {};
		List<String> a = new ArrayList<String>();
		char c;
		int start = 0, end = 0, len = s.length();
		for (; end < len; ++end) {
			c = s.charAt(end);
			if (c == delim) {
				String p = s.substring(start, end);
				a.add(trim ? p.trim() : p);
				start = end + 1;
			}
		}
		String p = s.substring(start, end);
		a.add(trim ? p.trim() : p);
		return (String[]) a.toArray(new String[a.size()]);
	}

}

 

 最后一种,也是最笨的一种-----最原始(因为webservice能够跨语言是因为它在网络上请求,回应的数据结构是固定的或者说是标准)

TIPS:所有的语言封装的webservice,其底层都是传输的相同的xml文件

所以我们也可以自己手动拼接SOAP XML然后用url发送代码如下

 

 

 

SoapTap类

 

import java.util.List;

/**
 * soap标签
 * @author Administrator
 *
 */
public class SoapTag {

	private String tagName;//标签名称
	private String tagValue;//标签值
	private String tagAttr;//标签属性
	private List<SoapTag> children;//子标签
	private SoapTag parent;//父类标签

	public String getTagName() {
		return tagName;
	}

	public void setTagName(String tagName) {
		this.tagName = tagName;
	}

	public String getTagValue() {
		return tagValue;
	}

	public void setTagValue(String tagValue) {
		this.tagValue = tagValue;
	}

	public List<SoapTag> getChildren() {
		return children;
	}

	public void setChildren(List<SoapTag> children) {
		this.children = children;
	}

	public SoapTag getParent() {
		return parent;
	}

	public void setParent(SoapTag parent) {
		this.parent = parent;
	}
	
	public String getTagAttr() {
		return tagAttr;
	}

	public void setTagAttr(String tagAttr) {
		this.tagAttr = tagAttr;
	}

	/**
	 * 转化为soapxml
	 * @return
	 */
	public String toSoapStr(StringBuilder retSoap){
		retSoap.append(createTagL());
		List<SoapTag> kids = getChildren();//拿到子节点
		if(kids != null&&kids.size()>0){
			for(SoapTag tag:kids){
				tag.toSoapStr(retSoap);
			}
		}
		retSoap.append(createTagR());
		return retSoap.toString();
	}
	/**
	 * 生成单个tag标签左边
	 * @param name
	 * @param value
	 * @return
	 */
	private String createTagL(){
		return "<"+getTagName()+">";
	}
    /**
     * 生成单个tag标签右边
     * @param name
     * @param value
     * @return
     */
    private String createTagR(){
    	return  "</"+getTagName()+">";
    }
}

  

工具类(项目中有特殊情况的逻辑,自己改吧改吧)

 

 

import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;


public class SoapHttpUtil {

    private static Logger log = Logger.getLogger(SoapHttpUtil.class);

    private static Map<String,String> tagMap = new LinkedHashMap<String, String>();
    
    static{
    	tagMap.put("Strcustid", null);
    	tagMap.put("TActivities", "CustId,ActiId,ActiType,ActiCodeNm,TitleNm,StartDt,EndDt,ActiStatus,ActiContent,MangerNms,CusPartis,InformantNm,ReportDt,Attachement");
    	tagMap.put("TContact", "CustId,Name,Sex,DepNm,Post,Email,FixTel,Mobile,IsMainContact");
    	tagMap.put("TIbs", "CustId,IbsId,Name,RelationType,RelationName,DepNm,Email,FixTel,Mobile,IsMainIbs");
    	tagMap.put("TabCondition", "ConField,ConHigh,ConLow,ConOption,ConSign");
    }
    


    /**
     * 调用机构CRM用户新增接口
     * @param serviceURL endpoint
     * @param paramMap
     * @return
     */
    public static String callService(String serviceURL,String custid){
        // 生成XML
        String soapBody = getSoapBody("ZcsGetcustinfoforcrm","urn:sap-com:document:sap:soap:functions:mc-style",custid);
        // 发送soap1.1请求
        Map<String,String> retSoap = doSoapPostRequest(serviceURL, soapBody, "utf-8");
        // 解析结果并返回
        StringBuilder retBuilder = new StringBuilder();
        return parseResponse(retSoap.get("RESULT"));
    }

    /**
     * 根据参数生成soap发送的xml
     * @param paramMap
     * @return
     */
    public static String getSoapBody(String actionurn,String namespace,String custids) {
    	StringBuilder sb = new StringBuilder();
    	sb.append("<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' ");
    	sb.append("   xmlns:urn='"+namespace+"'>\n");
    	sb.append("   <soapenv:Header/>\n");
    	sb.append("   <soapenv:Body>\n");
    	sb.append("      <urn:"+actionurn+">\n");
    	createSopTag(sb,tagMap,custids);//调用内部类
    	sb.append("      </urn:"+actionurn+">\n");
    	sb.append("   </soapenv:Body>\n");
    	sb.append("</soapenv:Envelope>");
    	return sb.toString();
    	
    }
    /**
     * 子类tag
     */
	private static void createSopTag(StringBuilder ret,Map<String,String> _tagMap,String param){
		for(Entry<String, String> entry:_tagMap.entrySet()){
			String key = entry.getKey();
			String value = entry.getValue();
			if(value == null){
				ret.append("<"+key+">" + param+"</"+key+">");
			}else{
				String values[] = value.split(",");//
				List<SoapTag> kid = new ArrayList<SoapTag>();
				List<SoapTag> itemKid = new ArrayList<SoapTag>();
				
				SoapTag parent = new SoapTag();
				parent.setTagName(key);
				parent.setTagValue("");
				
				SoapTag itemTag = new SoapTag();//itemTag
				itemTag.setTagName("item");
				kid.add(itemTag);
				
				for(String kidTag:values){
					SoapTag kidtag = new SoapTag();
					kidtag.setTagName(kidTag);
					kidtag.setTagValue("");
					itemKid.add(kidtag);
				}
				itemTag.setChildren(itemKid);
				parent.setChildren(kid);
				parent.toSoapStr(ret);//转化为tagxml
			}
		}
	}


    /**
     * 解析结果
     * @param respStr
     * @return
     */
    public static String parseResponse(String respStr){
    	StringBuilder active = new StringBuilder();//活动服务
    	StringBuilder ourcust = new StringBuilder();//我方联系人
    	StringBuilder cust = new StringBuilder();//客户方联系人
        Map<String, String> map = new HashMap<String, String>();
        Document  soupdoc = null;
        try {
        	soupdoc = Jsoup.parse(respStr);
        } catch (Exception e) {
            log.error("接口返回结果无法解析", e);
            throw new RuntimeException("接口返回结果无法解析", e);
        }
        Elements activities = soupdoc.select("TActivities");//活动服务记录
        Elements contact = soupdoc.select("TContact");//客户方联系人
        Elements ibs = soupdoc.select("TIbs");//我方跟踪团队
        parseEles(active,activities.get(0).children());
        parseEles(cust,contact.get(0).children());
        parseEles(ourcust,ibs.get(0).children());
        String activsJson = finalJson("active",active);
        String custjson = finalJson("cust",cust);
        String ourcustjson = finalJson("ourcust",ourcust);
        return "{" + activsJson +","+custjson+","+ourcustjson+"}";
    }
    /**
     * @return
     */
    private static String finalJson(String name ,StringBuilder json){
    	String _name = toJsonStyle(name);
    	String items = json.substring(0,json.lastIndexOf(","));
    	return ""+_name+":["+items+"]";
    }
    /**
     * item节点
     * @param retBuilder
     * @param els
     * @return
     */
    private static String parseEles(StringBuilder retBuilder,Elements els){
    	for(int i = 0 ;i < els.size();i++){
    		Element e = els.get(i);
    		parseChildren(retBuilder,e.children());
    	}
    	return null;
    }
    /**
     * 解析子节点
     * @return
     */
    private static String parseChildren(StringBuilder retBuilder,Elements els){
    	StringBuilder tempBuilder = new StringBuilder();
    	tempBuilder.append("{");
    	for(int i = 0 ;i < els.size();i++){
    		Element e = els.get(i);
    		String jitem = toJson(e);
    		tempBuilder.append(jitem+",");
    	}
    	String  temp = tempBuilder.substring(0, tempBuilder.lastIndexOf(","));
    	retBuilder.append(temp + "},");
    	return retBuilder.toString();
    }
    /**
     * 转换为json对象
     * @return
     */
    private static String toJson(Element e){
    	String name = e.tagName().toUpperCase();
    	String value = e.text();
    	return toJsonStyle(name) + ":" + toJsonStyle(value);
    }
    /**
     * 转换为json格式加双引号
     * @return
     */
    public static String toJsonStyle(String value){
    	return "\""+value+"\"";
    }

    /**
     * Post提交
     * @param urlstr
     * @param body
     * @return
     */
    public static Map<String, String> doSoapPostRequest(String urlstr, String body, String charset) {
        Map<String, String> reMap = new HashMap<String, String>();
        int resCode = -1; //返回状态值
        String resMsg = ""; //返回信息
        HttpURLConnection httpConn = null;
        OutputStream out = null;
        BufferedReader bfw = null;
        String line = null;
        StringBuffer sb = new StringBuffer();
        try {
            URL url = new URL(urlstr);
            httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setRequestMethod("POST");
            if (charset == null) {
                httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            }else {
                httpConn.setRequestProperty("Content-Type", "text/xml; charset=" + charset);
                httpConn.setRequestProperty("SOAPAction", urlstr);
            }
            httpConn.setUseCaches(false);
            httpConn.setInstanceFollowRedirects(false);
            httpConn.setConnectTimeout(5000);
            httpConn.setReadTimeout(10000);
            httpConn.setDoInput(true);
            httpConn.setDoOutput(true);

            out = httpConn.getOutputStream();
            out.write(body.getBytes("UTF-8"));
            out.flush();
        } catch (MalformedURLException e) {
            log.error("请求异常", e);
            throw new RuntimeException("请求异常", e);
        } catch (ProtocolException e) {
            log.error("请求异常", e);
            throw new RuntimeException("请求异常", e);
        } catch (IOException e) {
            log.error("请求异常", e);
            throw new RuntimeException("请求异常", e);
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        // 结果处理
        try {
            // 获取返回值
            resCode = httpConn.getResponseCode();
            resMsg = httpConn.getResponseMessage();
            if (resCode == 200) {
                bfw = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "utf-8"));
                while ((line = bfw.readLine()) != null) {
                    String curLine = line.trim();
                    if (!isEmpty(curLine))  sb.append(curLine);
                }
                reMap.put("CODE", "1");
                reMap.put("RESULT", sb.toString());
            } else {
                reMap.put("CODE","-1");
                reMap.put("RESULT","code=" + resCode+",msg=" + resMsg);
            }
        } catch (IOException e) {
            log.error("返回结果读取异常", e);
            throw new RuntimeException("返回结果读取异常", e);
        } finally {
            if (bfw != null) {
                try {
                    bfw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return reMap;
    }
    /**
     * 判断字符串是否为空
     * @param src
     * @return
     */
    public static boolean isEmpty(String src) {
        return src == null || src.trim().length() <= 0;
    }


    public static void main(String[] args) throws Exception{
        SoapHttpUtil ws = new SoapHttpUtil();
        String serviceURL = "test.do";
        String ret = ws.callService(serviceURL, "1000004106");
        System.out.println(ret);
    }

}

 

 

 

 

 

你可能感兴趣的:(webservice)