使用http的方式访问webService接口

使用http的方式访问webService接口

在工作中遇到的第一个难题 以前自己从来没有研究过,所以记录下来。

1. 使用接口访问工具测试接口是否可以正常访问

2. 了解访问接口的必备属性 wsdl 路径;namespace 命名空间 ;method 方法 ;str 入参。

3. 通过调试工具,获取到访问接口的入参和出参的xml

完成以上工作 我们可以开始coding啦 因为我的访问接口的入参出参 是用json格式的。大家可以根据自己入参出参进行改造。

1.访问接口的工具类

/**
     * 访问服务
     *
     * @param wsdl   wsdl地址
     * @param ns     命名空间
     * @param method 方法名
     * @param list   参数
     * @throws Exception
     */
    public synchronized static String accessService(String wsdl, String ns, String method, String jsonStr) throws Exception {
        String soapResponseData = "";
        //拼接SOAP
        StringBuffer soapRequestData = new StringBuffer("");
        soapRequestData.append( "");
        soapRequestData.append("");
        soapRequestData.append("");
        soapRequestData.append(""+jsonStr+" ");
        soapRequestData.append("");
        soapRequestData.append("" + "");
        PostMethod postMethod = new PostMethod(wsdl);
        // 然后把Soap请求数据添加到PostMethod中
        byte[] b = null;
        InputStream is = null;
        try {
            b = soapRequestData.toString().getBytes("utf-8");
            is = new ByteArrayInputStream(b, 0, b.length);
            RequestEntity re = new InputStreamRequestEntity(is, b.length, "text/xml; charset=UTF-8");
            postMethod.setRequestEntity(re);
            HttpClient httpClient = new HttpClient();
            httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(10*60*1000); //设置连接超时时间
			httpClient.getHttpConnectionManager().getParams().setSoTimeout(10*60*1000);//设置读取超时时间
            int status = httpClient.executeMethod(postMethod);
            if (status == 200) {
            	soapResponseData = getMesage(postMethod.getResponseBodyAsString());
            }
 
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                is.close();
            }
        }
        return soapResponseData;
    }

2.解析出参的工具类

/**
     * 解析参数
     * @throws Exception
     */
    public static String getMesage(String soapAttachment) throws Exception {
        if (soapAttachment != null && soapAttachment.length() > 0) {
        	      Document document=null;
        	      document=DocumentHelper.parseText(soapAttachment);
        	      //获取根元素
        	     Element root=document.getRootElement();
        	      //获取根元素下的所有子元素
        	     List list=root.elements();
        	     list=list.get(0).elements();
        	     String str = list.get(0).elementTextTrim("out");
            return str;
        } else {
            return "";
        }
    }
    

然后任务完成啦~

你可能感兴趣的:(2019)