1. 程式人生 > 其它 >華為北向RESTFUL 介面呼叫demo

華為北向RESTFUL 介面呼叫demo

專案中涉及到一個關於呼叫華為介面實現破損預警的專案

專案是基於Springboot搭建的,主要controller有

禁用SSL

DisableSSLCertificateCheckUtil
package XXX.socket.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.*;
import java.io.IOException;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public final class DisableSSLCertificateCheckUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(DisableSSLCertificateCheckUtil.class);
    private DisableSSLCertificateCheckUtil() {
    }
    public static void disableChecks() {
        try {
            new URL("https://192.168.2.3/").getContent();
        } catch (IOException e) {
// This invocation will always fail, but it will register the
// default SSL provider to the URL class.
        }
        try {
            SSLContext sslc;
            sslc = SSLContext.getInstance("TLS");
            TrustManager[] trustManagerArray = {new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                }
                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                }
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
            }};
            sslc.init(null, trustManagerArray, null);
            HttpsURLConnection.setDefaultSSLSocketFactory(sslc.getSocketFactory());
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });
        } catch (Exception e) {
            LOGGER.error("error msg:{}", e);
            throw new IllegalArgumentException("證書校驗異常!");
        }
    }
}
HttpsClientRequestFactory
package xxx.socket.controller;

import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustStrategy;
import org.springframework.http.client.SimpleClientHttpRequestFactory;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import java.net.HttpURLConnection;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * 相容調Https介面
 * @Author mazq
 * @Date 2020/06/04 17:16
 * @Param
 * @return
 */
public class HttpsClientRequestFactory extends SimpleClientHttpRequestFactory {
    @Override
    protected void prepareConnection(HttpURLConnection connection, String httpMethod) {
        try {
            if (!(connection instanceof HttpsURLConnection)) {// http協議
                //throw new RuntimeException("An instance of HttpsURLConnection is expected");
                super.prepareConnection(connection, httpMethod);
            }
            if (connection instanceof HttpsURLConnection) {// https協議,修改協議版本
                KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
                // 信任任何連結
                TrustStrategy anyTrustStrategy = new TrustStrategy() {
                    @Override
                    public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                        return true;
                    }
                };
                SSLContext ctx = SSLContexts.custom().useTLS().loadTrustMaterial(trustStore, anyTrustStrategy).build();
                ((HttpsURLConnection) connection).setSSLSocketFactory(ctx.getSocketFactory());
                HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
                super.prepareConnection(httpsConnection, httpMethod);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
RestTemplateUtils

 

package xxx.socket.controller;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * <pre>
 *      RestTemplate 遠端呼叫工具類
 * </pre>
 *
 * <pre>
 * </pre>
 */
@Component
public class RestTemplateUtils {


    public static RestTemplate geTemplate(){
        return new RestTemplate(new HttpsClientRequestFactory());
    }

    /**
     * GET請求呼叫方式
     * @Author mazq
     * @Date 2020/06/01 13:47
     * @Param [url, responseType, uriVariables]
     * @return org.springframework.http.ResponseEntity<T>
     */
    public static <T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Map<String, ?> uriVariables) {
        return geTemplate().getForEntity(url, responseType, uriVariables);
    }

    /**
     * POST請求呼叫方式
     * @Author mazq
     * @Date 2020/06/01 13:47
     * @Param [url, headers, body, responseType]
     * @return org.springframework.http.ResponseEntity<T>
     */
    public static <T> ResponseEntity<T> postForEntity(String url, HttpHeaders headers, Object requestBody , Class<T> responseType ){

        HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestBody, headers);
        return  geTemplate().postForEntity(url, requestEntity, responseType);
    }

    /**
     * PUT請求呼叫方式
     * @param url 請求URL
     * @param headers 請求頭引數
     * @param requestBody 請求引數體
     * @param responseType 返回物件型別
     * @param uriVariables URL中的變數,與Map中的key對應
     * @return ResponseEntity 響應物件封裝類
     */
    public static <T> ResponseEntity<T> put(String url, HttpHeaders headers, Object requestBody, Class<T> responseType, Map<String, ?> uriVariables) {
        HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestBody, headers);
        return geTemplate().exchange(url, HttpMethod.PUT, requestEntity, responseType, uriVariables);
    }

    /**
     * DELETE請求呼叫方式
     * @param url 請求URL
     * @param headers 請求頭引數
     * @param requestBody 請求引數體
     * @param responseType 返回物件型別
     * @param uriVariables URL中的變數,按順序依次對應
     * @return ResponseEntity 響應物件封裝類
     */
    public static <T> ResponseEntity<T> delete(String url, HttpHeaders headers, Object requestBody, Class<T> responseType, Object... uriVariables) {
        HttpEntity<Object> requestEntity = new HttpEntity<Object>(requestBody, headers);
        return geTemplate().exchange(url, HttpMethod.DELETE, requestEntity, responseType, uriVariables);
    }

    /**
     * 通用呼叫方式
     * @Author mazq
     * @Date 2020/06/01 13:37
     * @Param [url, method, requestEntity, responseType, uriVariables]
     * @return org.springframework.http.ResponseEntity<T>
     */
    public static <T> ResponseEntity<T> exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> responseType, Map<String, ?> uriVariables) {
        return geTemplate().exchange(url, method, requestEntity, responseType, uriVariables);
    }
}
WebSocketController(controller)
package xxx.socket.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.net.URISyntaxException;

@Controller
@RequestMapping(value = "/socket")
public class WebSocketController {

    private String prefix = "system/socket";

    /**
     * historyalarmpubu
     */
    @GetMapping("/historyalarmpubu")
    public String historyalarmpubu()
    {
        return prefix + "/historyalarmpubu";
    }


    @RequestMapping(value = "/testPostApi")
    @ResponseBody
    public Object testPostApi() throws URISyntaxException {
        RestTemplate restTemplate = new RestTemplate(new HttpsClientRequestFactory());

        //https ssl證書忽略
        DisableSSLCertificateCheckUtil.disableChecks();

        URI uri = new URI("https://192.168.888.999:26335/rest/plat/smapp/v1/sessions");
        HttpHeaders headers = new HttpHeaders();
        headers.add("Accept", "application/json");
        headers.add("Content-Type", "application/json;charset=UTF-8 ");
        //新增引數,因為HttpEntity裡面的引數是MultiValueMap型別的,所以使用這個map集合
        /*MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("grantType","password");
        map.add("userName", "userName");
        map.add("value", "passWord");*/
        String s = "{\"grantType\":\"password\",\"userName\": \"userName\",\"value\": \"passWord\"}";
        //新增請求的實體類,這裡第一個引數是要傳送的引數,第二個引數是請求頭裡的資料
        HttpEntity<Object> requestEntity = new HttpEntity<>(s, headers);
        //跟下面使用交換機的方法結果一樣
        ResponseEntity<String> exchange = restTemplate.exchange(uri, HttpMethod.PUT, requestEntity, String.class);
        JSONObject jsonObject = JSON.parseObject(exchange.getBody());
        System.out.println(jsonObject);
        return jsonObject;
    }

    @RequestMapping(value = "/testPostApi2")
    @ResponseBody
    public Object testPostApi2(String token) throws URISyntaxException {
        RestTemplate restTemplate = new RestTemplate(new HttpsClientRequestFactory());

        //https ssl證書忽略
        DisableSSLCertificateCheckUtil.disableChecks();

/*
        URI uri1 = new URI("https://192.168.888.999:26335/restconf/v1/data/tim-rtn-alarms:alarms/alarm-list?alarm-type-qualifier[]=14593&alarm-type-qualifier[]=14594&alarm-type-qualifier[]=14586");

        URI uri2 = new URI("https://192.168.888.999:26335/restconf/v1/data/ietf-alarms:alarms/alarm-list?limit=2000&start-time=2021-07-25T06:35:38Z&end-time=2021-7-30T14:35:38Z");

        URI uri3 = new URI("https://192.168.888.999:26335/restconf/v1/data/ietf-alarms:alarms/alarm-list?limit=2000&is-cleared=false&start-time=2021-07-25T06:35:38Z&end-time=2021-07-27T14:35:38Z");
*/

        URI uri = new URI("https://192.168.888.999:26335/restconf/v1/data/ietf-alarms:alarms/alarm-list?alarm-type-qualifier=268374017-14593&alarm-type-qualifier=268374017-14594");
        HttpHeaders headers = new HttpHeaders();
        headers.add("Accept", "application/json");
        headers.add("Content-Type", "application/json;charset=UTF-8 ");
        headers.add("X-Auth-Token", token);
        //新增引數,因為HttpEntity裡面的引數是MultiValueMap型別的,所以使用這個map集合
        /*MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("grantType","password");
        map.add("userName", "superuser");
        map.add("value", "Kcm_123456");*/
        String s1 = "{\"is-cleared\":false}";
        String s2 = "{\"is-cleared\":true,\"alarm-type-qualifier\": [\"14593\",\"14594\",\"14586\"]}";
        String s = "";

        //新增請求的實體類,這裡第一個引數是要傳送的引數,第二個引數是請求頭裡的資料
        HttpEntity<Object> requestEntity = new HttpEntity<>(s, headers);
        //跟下面使用交換機的方法結果一樣
        System.out.println(uri);
        ResponseEntity<String> exchange = restTemplate.exchange(uri, HttpMethod.GET, requestEntity, String.class);
        JSONObject jsonObject = JSON.parseObject(exchange.getBody());
        System.out.println(jsonObject);
        return jsonObject;
    }

    @RequestMapping(value = "/testPostApi3")
    @ResponseBody
    public Object testPostApi3(String token) throws URISyntaxException {
        RestTemplate restTemplate = new RestTemplate(new HttpsClientRequestFactory());

        //https ssl證書忽略
        DisableSSLCertificateCheckUtil.disableChecks();

        URI uri = new URI("https://192.168.888.999:26335/restconf/v1/data/ietf-alarms:alarms/alarm-list?alarm-type-qualifier=268374017-14586");
        HttpHeaders headers = new HttpHeaders();
        headers.add("Accept", "application/json");
        headers.add("Content-Type", "application/json;charset=UTF-8 ");
        headers.add("X-Auth-Token", token);
        String s = "";
        //新增請求的實體類,這裡第一個引數是要傳送的引數,第二個引數是請求頭裡的資料
        HttpEntity<Object> requestEntity = new HttpEntity<>(s, headers);
        //跟下面使用交換機的方法結果一樣
        System.out.println(uri);
        ResponseEntity<String> exchange = restTemplate.exchange(uri, HttpMethod.GET, requestEntity, String.class);
        JSONObject jsonObject = JSON.parseObject(exchange.getBody());
        System.out.println(jsonObject);
        return jsonObject;
    }
}

  

如遇到問題請聯絡博主第一時間修正刪除