RestTemplate使用技巧

有些场景中经常使用请求头设置请求参数,来获取token等信息。请看一下实例:

public class TokenUtil{
    //该例子没有请求体,从响应头中拿token
    public String getToken(){
        String url = "";
        HttpHeaders headers = new HttpHeaders();
        headers.add("X-Auth-Key","");
        headers.add("X-Auth-User","");
        headers.add("Content-Type","application/json;charset=UTF-8");
        headers.add("Accept","application/json;version=v6.0;charset=UTF-8");
        headers.add("Accept-Language","zh_CN");
        RestTemplate template = new RestTemplate();
        HttpEntity<String> requestEntity = new HttpEntity<String>(null,headers);
        ResponseEntity<String> responseEntity = template.exchange(url,HttpMethod.POST,requestEntity,String.class);
        HttpHeader responseHeaders =  responseEntity.getHeaders();
        //从响应头中拿token
        String token = responseHeaders.get("X-Auth-Token").get(0);
        return token;
    }
    //有请求体,有token,POST请求从响应体中拿返回结果
    public String getResult(){
        String url = "";
        HttpHeaders headers = new HttpHeaders();
        headers.add("X-Auth-Key","");
        headers.add("X-Auth-User","");
        headers.add("Content-Type","application/json;charset=UTF-8");
        headers.add("Accept","application/json;version=v6.0;charset=UTF-8");
        headers.add("Accept-Language","zh_CN");
        headers.add("X-Auth-Token",getToken())
        
        Map<String,Object> map = new HashMap<>();
        map.put("id","111111111");
        String httpBody = JSONObject.toJSONString(map);
        RestTemplate template = new RestTemplate();
        HttpEntity<String> requestEntity = new HttpEntity<String>(httpBody,headers);
        ResponseEntity<String> responseEntity = template.exchange(url,HttpMethod.POST,requestEntity,String.class);
        String responseBody =  responseEntity.getBody();
        return responseBody;
}

以上该例没有使用https协议的url,如果url中以https开头,那就要加一个东西在

RestTemplate template = new RestTemplate(new HttpsClientRequestFactory());

HttpsClientRequestFactory()类实现:

public class HttpsClientRequestFactory extends SimpleClientHttpRequestFactory{
    @Override
    protected void prepareConnection(HttpURLConnetion connection,String httpMethod){
        try{
            if(!(connection instanceof HttpURLConnetion)){
                throws new RuntimeException("An instance of HttpURLConnection is excepted ! ");
            }
            
            HttpsURLConnection httpsConnection = (HttpsURLConnection)connection;
            TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager(){
                    @Override
                    public void checkClientTrusted(X509Certificate[] x509Certificates,String s) throws CertificateException{}
        
                    @Override
                    public void checkServerTrusted(X509Certificte[] x509Certifictes,String s) throws CertificateException{}

                    @Override
                    public X509Certificate[] getAcceptedIssusers(){return null;}
                }
            };
         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();
        }
    }

    private static class MyCustomSSLSocketFactory extends SSLSocketFactory{
        private final SSLSocketFactory delegate;
        public MyCustomSSLSocketFactory(SSLSocketFactory delegate){this.delegate = delegate;}
        
        @Override
        public String[] getDefaultCipherSuites(){return delegate.getDefaultCipherSuites();}
        @Override
        public String[] getSupportedCipherSuites(){return delegate.getSupportedCipherSuites();}
        @Override
        public Socket createSocket(Socket socket,String s,int i,boolean b) throws IOException{
            final Socket underlyingSocket = delegate.createSocket(socket,s,i,b);
            return overrideProtocol(underlyingSocket);
        }
        @Override
        public Socket createSocket(String s,int i) throws IOException{
            final Socket underlyingSocket = delegate.createSocket(s,i);
            return overrideProtocol(underlyingSocket);
        }
        @Override
        public Socket createSocket(InetAddress inetAddress,int i) throws IOException{
            final Socket underlyingSocket = delegate.createSocket(inetAddress,i);
            return overrideProtocol(underlyingSocket);
        }
        @Override
        public Socket createSocket(InetAddress inetAddress,int i,InetAddress inetAddress1,int i1) throws IOException{
            final Socket underlyingSocket = delegate.createSocket(inetAddress,i,inetAddress1,i1);
            return overrideProtocol(underlyingSocket);
        }
        private Socket overrideProtocol(final Socket socket){
            if(!(socket instanceof SSLSocket)){
                throw new RuntimeException("An instance of SSLSocket is exception !");
            }
            ((Socket)socket).setEnabledProtocols(new String[]{"TLSv1"});
            return socket;
        }
    }
}

加上该HttpsClientRequestFactory工厂类即可实现对htpps协议的url访问

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值