La méthode d'appel sous-jacente de webService

Qu'est-ce que cela signifie d'utiliser le protocole Http dans le webservice

WebService utilise le protocole SOAP (Simple Object Access Protocol)
Le protocole Soap n'est utilisé que pour encapsuler des messages. Vous pouvez transmettre le message encapsulé via divers protocoles existants, tels que http, tcp/ip, smtp, etc. Vous pouvez même utiliser un protocole personnalisé une fois, et bien sûr, vous pouvez également utiliser le protocole https.
Soap est construit sur http. Pour le dire franchement, il utilise http pour transmettre du xml.

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

Le protocole SOAP est basé sur le protocole HTTP. La relation entre les deux est comme une autoroute transformée à partir d'une autoroute ordinaire. Une autoroute devient une autoroute après l'ajout de barrières.
WebService utilise le protocole HTTP pour transmettre les données et utilise le format XML pour encapsuler les données (c'est-à-dire quelle méthode appeler l'objet de service distant en XML, quels sont les paramètres passés et quel est le résultat de retour de l'objet de service) . Lorsque WebService envoie des requêtes et reçoit des résultats via le protocole HTTP, le contenu de la requête envoyée et le contenu du résultat sont encapsulés au format XML, et certains en-têtes de message HTTP spécifiques sont ajoutés pour illustrer le format de contenu du message HTTP. Le format du contenu est le protocole SOAP (simple object access protocol, simple object access protocol).
Tant que le préposé du magasin reçoit l'argent, il fournira la marchandise au client.Le préposé du magasin n'a pas besoin de se soucier de la nature du client, et le client n'a pas besoin de se soucier de la nature du préposé du magasin. De même, tant que le client WebService peut utiliser le protocole HTTP pour envoyer des données de requête XML dans un certain format au serveur WebService, le serveur WebService peut renvoyer les données de résultat XML dans un certain format via le protocole HTTP. l'autre partie utilise.

La méthode d'appel du webService natif sous-jacent :

1. Sur le serveur, utilisez la commande curl address pour obtenir le format de fichier xml.
2. Après avoir obtenu le format, passez la commande complète de curl sur le serveur pour tester et renvoyer les paramètres.
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. Analysez xml et accédez à des services tiers
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;
    }
}
modèle 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>"
}
appel 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;
    }
}

Je suppose que tu aimes

Origine blog.csdn.net/m0_46459413/article/details/129958695
conseillé
Classement