美文网首页
RestTemplate的(Http,Https)Get,Pos

RestTemplate的(Http,Https)Get,Pos

作者: 我是晓梦啊 | 来源:发表于2021-02-23 17:16 被阅读0次

1.RestTemplate

最近一直在做接口对接遇到很多问题,查询了大量资料
不知道引用的谁的,找了个好几个弄出来的.

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.Map;

public class HttpUtil {
    /**
     * 通过http协议发送post
     * @param url
     * @param param
     */
    public static String sendPostHttp(String url, Map<String, Object> param){
        RestTemplate restTemplate = new RestTemplate();
        //编码为utf-8
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        HttpHeaders headers = new HttpHeaders();
        //定义请求参数类型,这里用json所以是MediaType.APPLICATION_JSON
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, Object>> request = new HttpEntity<Map<String, Object>>(param, headers);
        ResponseEntity<String> entity = restTemplate.postForEntity(url, request, String.class);
        //获取3方接口返回的数据通过entity.getBody();它返回的是一个字符串;
        return entity.getBody();
    }
    /**
     * 通过http协议发送get
     * @param url
     * @param param
     */
    public static String sendGetHttp(String url, Map<String, Object> param){
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        //处理参数
        StringBuilder builder = new StringBuilder();
        if (param != null) {
            for (String key : param.keySet()) {
                builder.append(key + "=" + param.get(key) + "&");
            }
        }
        ResponseEntity<String> res = restTemplate.getForEntity(url+"?"+builder, String.class);
        return res.getBody();
    }


    /**
     * 使用https协议发送post
     * @param url 请求地址
     * @param param 参数
     */
    public static String sendPostHttps(String url, Map<String, String> param) {
        RestTemplate restTemplate = new RestTemplate(new HttpsClientRequestFactory());
        //编码为utf-8
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        HttpHeaders headers = new HttpHeaders();
        //定义请求参数类型,这里用json所以是MediaType.APPLICATION_JSON
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, String>> request = new HttpEntity<Map<String, String>>(param, headers);
        ResponseEntity<String> entity = restTemplate.postForEntity(url, request, String.class);
        //获取3方接口返回的数据通过entity.getBody();它返回的是一个字符串;
        return entity.getBody();
    }

    /**
     * 使用https协议发送get
     * @param url 请求地址
     * @param param 参数
     */
    public static String sendGetHttps(String url, Map<String, Object> param) {
        RestTemplate restTemplate = new RestTemplate(new HttpsClientRequestFactory());
        //编码为utf-8
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        //处理参数
        StringBuilder builder = new StringBuilder();
        if (param != null) {
            for (String key : param.keySet()) {
                builder.append(key + "=" + param.get(key) + "&");
            }
        }
        ResponseEntity<String> res = restTemplate.getForEntity(url+"?"+builder, String.class);
        return res.getBody();
    }

}

这个类需要配合下面的类去使用

import org.springframework.http.client.SimpleClientHttpRequestFactory;
import javax.net.ssl.*;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.Socket;
import java.security.cert.X509Certificate;

/**
 * 声明:此代码摘录自https://blog.csdn.net/wltsysterm/article/details/80977455
 */
public class HttpsClientRequestFactory extends SimpleClientHttpRequestFactory {

    @Override
    protected void prepareConnection(HttpURLConnection connection, String httpMethod) {
        try {
            if (!(connection instanceof HttpsURLConnection)) {
                throw new RuntimeException("An instance of HttpsURLConnection is expected");
            }

            HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;

            TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return null;
                        }
                        @Override
                        public void checkClientTrusted(X509Certificate[] certs, String authType) {
                        }
                        @Override
                        public void checkServerTrusted(X509Certificate[] certs, String authType) {
                        }

                    }
            };
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            httpsConnection.setSSLSocketFactory(new MyCustomSSLSocketFactory(sslContext.getSocketFactory()));

            httpsConnection.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });

            super.prepareConnection(httpsConnection, httpMethod);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * We need to invoke sslSocket.setEnabledProtocols(new String[] {"SSLv3"});
     * see http://www.oracle.com/technetwork/java/javase/documentation/cve-2014-3566-2342133.html (Java 8 section)
     */
    // SSLSocketFactory用于创建 SSLSockets
    private static class MyCustomSSLSocketFactory extends SSLSocketFactory {

        private final SSLSocketFactory delegate;

        public MyCustomSSLSocketFactory(SSLSocketFactory delegate) {
            this.delegate = delegate;
        }

        // 返回默认启用的密码套件。除非一个列表启用,对SSL连接的握手会使用这些密码套件。
        // 这些默认的服务的最低质量要求保密保护和服务器身份验证
        @Override
        public String[] getDefaultCipherSuites() {
            return delegate.getDefaultCipherSuites();
        }

        // 返回的密码套件可用于SSL连接启用的名字
        @Override
        public String[] getSupportedCipherSuites() {
            return delegate.getSupportedCipherSuites();
        }


        @Override
        public Socket createSocket(final Socket socket, final String host, final int port,
                                   final boolean autoClose) throws IOException {
            final Socket underlyingSocket = delegate.createSocket(socket, host, port, autoClose);
            return overrideProtocol(underlyingSocket);
        }


        @Override
        public Socket createSocket(final String host, final int port) throws IOException {
            final Socket underlyingSocket = delegate.createSocket(host, port);
            return overrideProtocol(underlyingSocket);
        }

        @Override
        public Socket createSocket(final String host, final int port, final InetAddress localAddress,
                                   final int localPort) throws
                IOException {
            final Socket underlyingSocket = delegate.createSocket(host, port, localAddress, localPort);
            return overrideProtocol(underlyingSocket);
        }

        @Override
        public Socket createSocket(final InetAddress host, final int port) throws IOException {
            final Socket underlyingSocket = delegate.createSocket(host, port);
            return overrideProtocol(underlyingSocket);
        }

        @Override
        public Socket createSocket(final InetAddress host, final int port, final InetAddress localAddress,
                                   final int localPort) throws
                IOException {
            final Socket underlyingSocket = delegate.createSocket(host, port, localAddress, localPort);
            return overrideProtocol(underlyingSocket);
        }

        private Socket overrideProtocol(final Socket socket) {
            if (!(socket instanceof SSLSocket)) {
                throw new RuntimeException("An instance of SSLSocket is expected");
            }
            ((SSLSocket) socket).setEnabledProtocols(new String[]{"TLSv1"});
            return socket;
        }
    }
}

相关文章

  • RestTemplate的(Http,Https)Get,Pos

    1.RestTemplate 最近一直在做接口对接遇到很多问题,查询了大量资料不知道引用的谁的,找了个好几个弄出来...

  • java发送http请求

    restTemplate get请求 post请求 apache.http.client get请求 post请求...

  • iOS AFNetworking 提示 "The re

    原因: iOS9之后, 苹果把原http协议改成了https协议, 所以不能直接在http协议下使用GET/POS...

  • RestTemplate发送HTTP、HTTPS请求

    本文转载文章:RestTemplate发送HTTP、HTTPS请求基础知识微服务都是以HTTP接口的形式暴露自身服...

  • HTTP协议类

    HTTP协议的主要特点 HTTP 报文的组成部分 HTTP 方法 GET 获取资源 POS...

  • android--网络编程

    Http请求方式 常用只有Post与Get。 HttpURLConnection的用法 申明网络权限! 使用pos...

  • RequestsLibrary使用

    安装 先要安装requests,再安装requestsLibrary 使用 http请求的7种方法 get pos...

  • java调用接口小结

    最近因为系统需要,需要采用 http 调用对方的服务器接口,GET,POST 都有,记录一下GET 请求: POS...

  • DolphinScheduler-api调度之RestTempl

    1. 通过RestTemplate 的工具类进行封装然后调用 get 和post 通过RestTemplate 进...

  • HTTP/HTTPS与GET/POST

    Http定义了与服务器交互的不同方法,最基本的方法有4种,分别是GET,POST,PUT,DELETE。 URL全...

网友评论

      本文标题:RestTemplate的(Http,Https)Get,Pos

      本文链接:https://www.haomeiwen.com/subject/xhfdfltx.html