http调用webservice工具类

最近遇到个webservice的对接,上百个接口,但是统一都是入参出参都是统一一个json

所以写了一个工具类,下面上代码

需要用到的jar

<dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
</dependency>

代码

public static HashMap<String,String> getData(String url,String op, String xmlPara){
    //统一接口,可以统一接入封装xml
    xmlPara = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
            "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">\n" +
            "  <soap12:Body>\n" +
            //这里我加入op是因为接口统一都是已接口名字作为入参的xml节点
            "    <"+op+" xmlns=\"http://tempurl.org\">\n" +
            "      <as_inputjson>"+xmlPara+"</as_inputjson>\n" +
            "    </"+op+">\n" +
            "  </soap12:Body>\n" +
            "</soap12:Envelope>" ;
    HashMap<String,String> res = new HashMap<>();
    //这里写你的地址url
    String endpoint = url+"?op"+op;
    PostMethod postMethod = new PostMethod(endpoint);
    byte[] b;
    try {
        b = xmlPara.getBytes("utf-8");
        InputStream is = new ByteArrayInputStream(b,0,b.length);
        InputStreamRequestEntity re = new InputStreamRequestEntity(is,b.length,"application/soap+xml; charset=utf-8");
        //把Soap请求数据添加到PostMethod中
        postMethod.setRequestEntity(re);

        //生成一个HttpClient对象,并发出postMethod请求
        HttpClient httpClient = new HttpClient();
        int statusCode = httpClient.executeMethod(postMethod);
        if(200==statusCode){
            String getServerData =  postMethod.getResponseBodyAsString();
            //System.out.println("----->"+getServerData);
            //获取返回值状态标识,标识为0:成功;非0:失败
            res.put("status", "0");
            //这里的op也是一样的作用,返回都是接口名字+Result作为返回节点,我这里都是json返回,如果需要xml返回自行解析就好
            res.put("msg", getServerData.substring(getServerData.indexOf("<"+op+"Result>")+18,getServerData.indexOf("</"+op+"Result>")));
        }
    } catch (Exception e) {
        res.put("status", "1");
        res.put("msg", e.toString());
        e.printStackTrace();
    }
    return res;
}
喜欢(0) 打赏

评论抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

觉得文章有用就打赏一下吧

支付宝扫一扫打赏

微信扫一扫打赏