webService の基礎となる呼び出しメソッド

WebサービスでプロトコルHttpを使用することは何を意味しますか

WebService は SOAP (Simple Object Access Protocol) プロトコルを使用します。SOAP
プロトコルはメッセージをカプセル化するためにのみ使用されます。カプセル化されたメッセージは、http、tcp/ip、smtp などのさまざまな既存のプロトコルを介して送信できます。カスタム プロトコルを一度だけ使用することもできます。もちろん、https プロトコルも使用できます。
Soap は http 上に構築されており、端的に言えば、xml の送信に http を使用します。

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

SOAP プロトコルは HTTP プロトコルをベースにしており、両者の関係は、一般の高速道路を高速道路に変換したようなもので、高速道路に障壁を追加すると高速道路になります。
WebService は、HTTP プロトコルを使用してデータを送信し、XML 形式を使用してデータをカプセル化します (つまり、XML でリモート サービス オブジェクトを呼び出すメソッド、渡されるパラメータ、およびサービス オブジェクトの戻り結果) 。WebService が HTTP プロトコルを通じてリクエストを送信し、結果を受信する場合、送信されたリクエストのコンテンツと結果のコンテンツは XML 形式でカプセル化され、HTTP メッセージのコンテンツ形式を示すためにいくつかの特定の HTTP メッセージ ヘッダーが追加されます。これらの特定の HTTP メッセージ ヘッダーと XMLコンテンツの形式はSOAPプロトコル(シンプルオブジェクトアクセスプロトコル、シンプルオブジェクトアクセスプロトコル)です。
店員はお金さえ受け取れば商品を顧客に提供するので、店員は顧客の性格を気にする必要がなく、顧客も店員の性格を気にする必要がない。同様に、WebService クライアントが HTTP プロトコルを使用して XML 要求データを特定の形式で WebService サーバーに送信できる限り、WebService サーバーは HTTP プロトコルを通じて XML 結果データを特定の形式で返すことができます。相手が使っています。

ネイティブの基礎となる WebService の呼び出しメソッド:

1. サーバー上で、curl address コマンドを使用して、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