webService的底层调用方式

webservice中采用协议Http,是指什么意思

WebService使用的是 SOAP (Simple Object Access Protocol)协议
Soap协议只是用来封装消息用的。封装后的消息你可以通过各种已有的协议来传输,比如http,tcp/ip,smtp,等等,你甚至还一次用自定义的协议,当然也可以用https协议。
Soap建立在http上,说白了是用http传送xml而已。

SOAP协议= HTTP协议+ XML数据格式

SOAP协议是基于HTTP协议的,两者的关系就好比高速公路是基于普通公路改造的,在一条公路上加上隔离栏后就成了高速公路。
WebService采用HTTP协议传输数据,采用XML格式封装数据(即XML中说明调用远程服务对象的哪个方法,传递的参数是什么,以及服务对象的返回结果是什么)。WebService通过HTTP协议发送请求和接收结果时,发送的请求内容和结果内容都采用XML格式封装,并增加了一些特定的HTTP消息头,以说明HTTP消息的内容格式,这些特定的HTTP消息头和XML内容格式就是SOAP协议(simple object access protocol,简单对象访问协议) 。
商店的服务员只要收到了钱就给客户提供货物,商店服务员不用关心客户是什么性质的人,客户也不用关心商店服务员是什么性质的人。同样,WebService客户端只要能使用HTTP协议把遵循某种格式的XML请求数据发送给WebService服务器,WebService服务器再通过HTTP协议返回遵循某种格式的XML结果数据就可以了,WebService客户端与服务器端不用关心对方使用的是什么编程语言。

原生底层webService的调用方式:

1、在服务器上,通过 curl 地址 命令来获取xml文件格式。
2、获取到格式后,在服务器上通过curl的完整命令,进行测试返参等。
curl --location --request POST '地址' \
--header 'Content-Type: text/xml' \
--data '<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:hjb="http://localhost:8080/hjbjWebService">
   <soapenv:Header/>
   <soapenv:Body>
      <xxx:xxxxxx soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
         <in0 xsi:type="xsd:string">入参</in0>
      </xxx:xxxxxx>
   </soapenv:Body>
</soapenv:Envelope>'
3、解析xml,访问三方服务
package com.ylz.bjyf.ggfw.apps.proxy.handler.ws;

import com.alibaba.fastjson.JSONObject;
import com.ylz.bjyf.ggfw.apps.proxy.exception.FailException;
import com.ylz.bjyf.ggfw.apps.proxy.exception.ProxyException;
import com.ylz.bjyf.ggfw.apps.proxy.handler.HttpHandler;
import com.ylz.bjyf.ggfw.apps.proxy.handler.ProxyHandler;
import com.ylz.bjyf.ggfw.apps.proxy.util.HttpUtils;
import com.ylz.bjyf.ggfw.apps.service.entity.YwztProxy;
import com.ylz.bjyf.ggfw.common.util.XmlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestClientException;

import java.util.List;
import java.util.Map;

@Slf4j
@Component("proxy.wsHttp")
public class wsHttpHandler extends ProxyHandler {
    
    

    @Autowired
    private HttpUtils httpUtils;

    @Override
    protected MultiValueMap<String, Object> encodeParam(String serialno, JSONObject config, MultiValueMap<String, Object> param) throws FailException, ProxyException {
    
    
        //config传参中,传入xml模板
        String[] keyList = config.getString("keyList").split(",");
        //获取模板xml
        String xml = config.getString("xml");

        //替换方法名
        if (config.containsKey("func")) {
    
    
            xml.replace("{
    
    {func}}", config.getString("func"));
        }
        //替换命名空间
        if (config.containsKey("namespace")) {
    
    
            xml.replace("{
    
    {namespace}}", config.getString("namespace"));
        }
        //替换参数
        for (int i = 0; i < keyList.length; i++) {
    
    
            String key = keyList[i];
            if (param.get(key).size() > 0 && param.get(key).get(0) != null) {
    
    
                xml = xml.replace("{
    
    {" + key + "}}", param.get(key).get(0).toString());
            } else {
    
    
                xml = xml.replace("{
    
    {" + key + "}}", "");
            }
        }
        MultiValueMap<String, Object> paramMapPage = new LinkedMultiValueMap<>();
        paramMapPage.add("data", xml);
        return paramMapPage;
    }

    @Override
    protected String excute(YwztProxy proxy, JSONObject config, MultiValueMap<String, Object> param) throws ProxyException, FailException {
    
    
        //构造http请求头
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("text/xml;charset=UTF-8");
        headers.setContentType(type);
        if (config.containsKey(HttpHandler.HEADER_STR) && !StringUtils.isEmpty(config.get(HttpHandler.HEADER_STR))) {
    
    
            JSONObject headerParams = config.getJSONObject(HttpHandler.HEADER_STR);
            for (Map.Entry k : headerParams.entrySet()) {
    
    
                headers.set(k.getKey().toString(), k.getValue().toString());
            }
        }
        HttpEntity<String> formEntity = new HttpEntity<>(param.get("data").get(0).toString(), headers);
        String resultStr = null;
        try {
    
    
            resultStr = httpUtils.postForString(proxy.getUrl(), HttpMethod.POST, formEntity);
        } catch (RestClientException e) {
    
    
            log.error(ProxyException.DEFAULT_MESSAGE, e);
            throw new FailException("调用接口异常:" + e.getMessage());
        }
        if (resultStr == null) {
    
    
            throw new FailException("调用接口失败");
        }
        return resultStr;
    }

    @Override
    protected String decodeResult(String serialno, JSONObject config, String resultString) {
    
    
        resultString = StringEscapeUtils.unescapeXml(resultString);
        if (config.containsKey("resultTag")) {
    
    
            return XmlUtils.getTextForElement(resultString, config.getString("resultTag"));
        } else if (config.containsKey("delText")) {
    
    
            return resultString.replace(config.getString("delText"), "");
        }
        return resultString;
    }
}
xml模板:
{
    
    
  "resultTag": "hjbjcxResponse",
  "keyList": "json",
  "xml": "<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:hjb=\"xxxxxxxx\"><soapenv:Header/><soapenv:Body><xxx:xxxxxx soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"><in0 xsi:type=\"xsd:string\">{
    
    {json}}</in0></xxx:xxxxxx></soapenv:Body></soapenv:Envelope>"
}
http调用:
package com.ylz.bjyf.ggfw.apps.proxy.util;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.ylz.bjyf.ggfw.apps.proxy.exception.FailException;
import com.ylz.bjyf.ggfw.apps.proxy.exception.ProxyException;
import io.vertx.core.json.JsonObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Slf4j
@Service
public class HttpUtils {
    
    

    @Autowired
    RestTemplate restTemplate;

    public String postForString(String url, HttpMethod method, HttpEntity<?> requestEntity) throws FailException, ProxyException {
    
    
        try {
    
    
            if (HttpMethod.GET.equals(method)) {
    
    
                return getForString(url, method, requestEntity);
            }

            ResponseEntity<String> result = restTemplate.exchange(url, method, requestEntity, String.class);
            if (HttpStatus.OK.equals(result.getStatusCode())) {
    
    
                return result.getBody();
            } else {
    
    
                throw new FailException("http调用失败:", result.getBody());
            }
        } catch (RestClientException e) {
    
    
            throw new ProxyException(e);
        }
    }

    public String getForString(String url, HttpMethod method, HttpEntity<?> requestEntity) throws FailException, ProxyException {
    
    
        try {
    
    

            Map<String, Object> map = null;

            if (requestEntity.getBody() != null) {
    
    
                if (requestEntity.getBody().toString().startsWith("{") && requestEntity.getBody().toString().endsWith("}")) {
    
    
                    try {
    
    
                        map = JSONObject.parseObject(requestEntity.getBody().toString());
                        for (Map.Entry<String, Object> entry : map.entrySet()) {
    
    
                            url = url_expand(url, entry.getKey(), entry.getValue().toString());
                        }
                    } catch (JSONException e) {
    
    
                        log.error("解析json失败", e);
                    }
                }

            }
            log.info("get请求最终URL"+url);
            HttpHeaders headers = requestEntity.getHeaders();
            HttpHeaders headers2 = new HttpHeaders();
            if (headers != null) {
    
    
                for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
    
    
                    if (HttpHeaders.CONTENT_TYPE.equalsIgnoreCase(entry.getKey())) {
    
    
                        headers2.add(entry.getKey(), entry.getValue().get(0));
                    }
                }
            }

            HttpEntity<Object> formEntity = new HttpEntity<>(null, headers2);
            log.info("get请求最终头"+formEntity.getHeaders().toString());
            ResponseEntity<String> result = restTemplate.exchange(url, method, formEntity, String.class);
            if (HttpStatus.OK.equals(result.getStatusCode())) {
    
    
                return result.getBody();
            } else {
    
    
                throw new FailException("http调用失败:", result.getBody());
            }
        } catch (RestClientException e) {
    
    
            throw new ProxyException(e);
        }

    }

    private static final String url_expand(String url, String key, String value) {
    
    
        if (StringUtils.isEmpty(url) || StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) {
    
    
            return url;
        }
        if (url.contains("?")) {
    
    
            url += "&" + key + "=" + value;
        } else {
    
    
            url += "?" + key + "=" + value;
        }
        return url;
    }
}

猜你喜欢

转载自blog.csdn.net/m0_46459413/article/details/129958695
今日推荐