The underlying calling method of webService

What does it mean to use the protocol Http in webservice

WebService uses the SOAP (Simple Object Access Protocol) protocol.
The Soap protocol is only used to encapsulate messages. You can transmit the encapsulated message through various existing protocols, such as http, tcp/ip, smtp, etc. You can even use a custom protocol once, and of course you can also use the https protocol.
Soap is built on http. To put it bluntly, it uses http to transmit xml.

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

The SOAP protocol is based on the HTTP protocol. The relationship between the two is like a highway transformed from an ordinary highway. A highway becomes a highway after adding barriers.
WebService uses the HTTP protocol to transmit data, and uses the XML format to encapsulate the data (that is, which method to call the remote service object in XML, what are the parameters passed, and what is the return result of the service object). When WebService sends requests and receives results through the HTTP protocol, the sent request content and result content are encapsulated in XML format, and some specific HTTP message headers are added to illustrate the content format of the HTTP message. These specific HTTP message headers and XML The content format is the SOAP protocol (simple object access protocol, simple object access protocol).
As long as the store attendant receives the money, he will provide the customer with the goods. The store attendant does not need to care about the nature of the customer, and the customer does not need to care about the nature of the store attendant. Similarly, as long as the WebService client can use the HTTP protocol to send XML request data in a certain format to the WebService server, the WebService server can return the XML result data in a certain format through the HTTP protocol. Care about what programming language the other party is using.

The calling method of the native underlying webService:

1. On the server, use the curl address command to obtain the xml file format.
2. After obtaining the format, pass the complete command of curl on the server to test and return parameters.
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. Parse xml and access third-party services
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 template:
{
    
    
  "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 call:
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;
    }
}

Guess you like

Origin blog.csdn.net/m0_46459413/article/details/129958695