WebService系列之HttpClient调用WebService接口

测试工具下载soapui测试

http://ws.webxml.com.cn/WebServices/WeatherWS.asmx?wsdl
在这里插入图片描述

在这里插入图片描述

package com.extra.credit.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;
import java.util.List;

/**
 * <pre>
 *      工具类:HttpClient方式调用webService服务
 * </pre>
 *
 * <pre>
 * @author nicky ma
 * 修改记录
 *    修改后版本:     修改人:  修改日期: 2021/03/11 10:05  修改内容:
 * </pre>
 */
@Component
public class WSHttpClientUils {

    static Logger log = LoggerFactory.getLogger(WSHttpClientUils.class);

    /**
     *  HttpClient方式调用webservice api <br>
     * @Author mazq
     * @Date 2021/03/11 10:14
     * @Param [point, params, methodName]
     * @return java.lang.String
     */
    public static String doPostWebServiceURL(String point, String params, String soapAction)throws Exception {
        String result = "";
        // 创建HttpClientBuilder
	        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
	        // HttpClient
	        CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
            HttpPost httpPost = new HttpPost(point);
        try {
            httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
            httpPost.setHeader("SOAPAction", soapAction);
            StringEntity data = new StringEntity(params,
                    Charset.forName("UTF-8"));
            httpPost.setEntity(data);
            CloseableHttpResponse response = closeableHttpClient
                    .execute(httpPost);
            HttpEntity httpEntity = response.getEntity();
            if (httpEntity != null) {
                result = EntityUtils.toString(httpEntity, "UTF-8");
            }
        } catch (Exception e) {
            log.error("调用远程WebService接口异常:{}" , e);
            throw e;
        }finally {
            IOUtils.closeQuietly(closeableHttpClient);
        }
        return result;
    }

    /**
     * xml转换为JSONObject <br>
     * @Author nicky ma
     * @Date 2021/03/11 10:01
     * @Param [xmlStr]
     * @return com.alibaba.fastjson.JSONObject
     */
    public static JSONObject xml2Json(String xmlStr) throws DocumentException {
        Document doc = DocumentHelper.parseText(xmlStr);
        JSONObject json = new JSONObject();
        doParseXmlElements(doc.getRootElement() , json);
        return json;
    }

    /**
     * xml Document Elements解析 <br>
     * @Author nicky ma
     * @Date 2021/03/11 10:01
     * @Param [element, json]
     * @return void
     */
    public static void doParseXmlElements(Element element, JSONObject json) {
        List<Element> chdEl = element.elements();
        for(Element e : chdEl){
            if (!e.elements().isEmpty()) {
                JSONObject chdjson = new JSONObject();
                doParseXmlElements(e, chdjson);
                Object o = json.get(e.getName());
                if (o != null) {
                    JSONArray jsona = null;
                    if (o instanceof JSONObject) {
                        JSONObject jsono = (JSONObject) o;
                        json.remove(e.getName());
                        jsona = new JSONArray();
                        jsona.add(jsono);
                        jsona.add(chdjson);
                    }
                    if (o instanceof JSONArray) {
                        jsona = (JSONArray) o;
                        jsona.add(chdjson);
                    }
                    json.put(e.getName(), jsona);
                } else {
                    if (!chdjson.isEmpty()) {
                        json.put(e.getName(), chdjson);
                    }
                }
            } else {
                if (!e.getText().isEmpty()) {
                    json.put(e.getName(), e.getText());
                }
            }
        }
    }

}

protected Map<String , String> obtainTokenByHttp(String paramJson , String url) throws Exception {
     StringBuffer soapRequestParams = new StringBuffer();
     soapRequestParams.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://service.webservice.catalog.infotrust.com\">");
     soapRequestParams.append("<soapenv:Header/>");
     soapRequestParams.append("<soapenv:Body>");
     soapRequestParams.append("<ser:getToken>");
     soapRequestParams.append("<ser:in0>"+paramJson+"</ser:in0>");
     soapRequestParams.append("</ser:getToken>");
     soapRequestParams.append("</soapenv:Body>");
     soapRequestParams.append("</soapenv:Envelope>");
     logger.warn(String.format("request params:%s", soapRequestParams.toString()));

     String returnDatabase = WSHttpClientUils.doPostWebServiceURL(url , soapRequestParams.toString(),"");
     logger.warn(String.format("xml string:%s" , returnDatabase));
     com.alibaba.fastjson.JSONObject jsonObject = WSHttpClientUils.xml2Json(returnDatabase);
     com.alibaba.fastjson.JSONObject body = jsonObject.getJSONObject("Body");
     com.alibaba.fastjson.JSONObject getSafeTokenResponse = body.getJSONObject("getSafeTokenResponse");
     String out = getSafeTokenResponse.getString("out");
     com.alibaba.fastjson.JSONObject outJson = JSON.parseObject(out);
     String code = outJson.getString("code");
     String message = outJson.getString("message");
     String token = "";
     logger.warn(String.format("webservice api返回数据,code:%s,message:%s",code,
             message));
     if ("200".equals(code)) {
         token = outJson.getString("token");
     }
     if (logger.isInfoEnabled()) {
         logger.info(String.format("api token:%s", token));
     }
     Map<String,String> result = new HashMap<String, String>(2);
     result.put("token",token);
     return result;
 }
smileNicky CSDN认证博客专家 分布式 Java Spring
java程序员,软件工程专业,专注于sql调优,SpringBoot,spring框架学习,个人邮箱nickypm@foxmail.com,公众号nickymp
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 岁月 设计师:pinMode 返回首页
实付 9.90元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值