springboot中使用RestTemplate

一。导入依赖

 pom.xml

  

 
            org.apache.httpcomponents 
            httpclient 
        

 

二。springboot引入配置 


package com.jztey.gxdemo; 

import java.nio.charset.Charset; 
import java.security.KeyManagementException; 
import java.security.KeyStoreException; 
import java.security.NoSuchAlgorithmException; 
import java.util.Iterator; 
import java.util.List; 

import org.apache.http.impl.client.CloseableHttpClient; 
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; 
import org.springframework.context.annotation.Bean; 
import org.springframework.context.annotation.Configuration; 
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; 
import org.springframework.http.converter.HttpMessageConverter; 
import org.springframework.http.converter.StringHttpMessageConverter; 
import org.springframework.web.client.RestOperations; 
import org.springframework.web.client.RestTemplate; 

@Configuration 
public class RestConfiguration { 
    @Bean 
    @ConditionalOnMissingBean({RestOperations.class, RestTemplate.class}) 
    public RestOperations restOperations() { 

//        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); 
//        requestFactory.setReadTimeout(5000); 
//        requestFactory.setConnectTimeout(5000); 

        CloseableHttpClient httpClient = null; 
        try { 
            httpClient = HttpClientUtils.acceptsUntrustedCertsHttpClient(); 
        } catch (KeyManagementException e) { 
            // TODO Auto-generated catch block 
            e.printStackTrace(); 
        } catch (KeyStoreException e) { 
            // TODO Auto-generated catch block 
            e.printStackTrace(); 
        } catch (NoSuchAlgorithmException e) { 
            // TODO Auto-generated catch block 
            e.printStackTrace(); 
        } 
        HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); 

        RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory); 

        // 使用 utf-8 编码集的 conver 替换默认的 conver(默认的 string conver 的编码集为 "ISO-8859-1") 
        List> messageConverters = restTemplate.getMessageConverters(); 
        Iterator> iterator = messageConverters.iterator(); 
        while (iterator.hasNext()) { 
            HttpMessageConverter converter = iterator.next(); 
            if (converter instanceof StringHttpMessageConverter) { 
                iterator.remove(); 
            } 
        } 
        messageConverters.add(new StringHttpMessageConverter(Charset.forName("UTF-8"))); 
        return restTemplate; 
    } 
}

 

由于需要支持https 需要自定义httpclient  注入

 

package com.jztey.gxdemo; 

import org.apache.http.config.Registry; 
import org.apache.http.config.RegistryBuilder; 
import org.apache.http.conn.socket.ConnectionSocketFactory; 
import org.apache.http.conn.socket.PlainConnectionSocketFactory; 
import org.apache.http.conn.ssl.NoopHostnameVerifier; 
import org.apache.http.conn.ssl.SSLConnectionSocketFactory; 
import org.apache.http.impl.client.CloseableHttpClient; 
import org.apache.http.impl.client.HttpClientBuilder; 
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; 
import org.apache.http.ssl.SSLContextBuilder; 
import org.apache.http.ssl.TrustStrategy; 

import javax.net.ssl.HostnameVerifier; 
import javax.net.ssl.SSLContext; 
import java.security.KeyManagementException; 
import java.security.KeyStoreException; 
import java.security.NoSuchAlgorithmException; 
import java.security.cert.CertificateException; 
import java.security.cert.X509Certificate; 

/** 
 * Created by Administrator on 2015/6/8. 
 */ 
public class HttpClientUtils { 

    public static CloseableHttpClient acceptsUntrustedCertsHttpClient() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException { 
        HttpClientBuilder b = HttpClientBuilder.create(); 

        // setup a Trust Strategy that allows all certificates. 
        // 
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { 
            public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { 
                return true; 
            } 
        }).build(); 
        b.setSSLContext(sslContext); 

        // don't check Hostnames, either. 
        //      -- use SSLConnectionSocketFactory.getDefaultHostnameVerifier(), if you don't want to weaken 
        HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE; 

        // here's the special part: 
        //      -- need to create an SSL Socket Factory, to use our weakened "trust strategy"; 
        //      -- and create a Registry, to register it. 
        // 
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier); 
        Registry socketFactoryRegistry = RegistryBuilder.create() 
                .register("http", PlainConnectionSocketFactory.getSocketFactory()) 
                .register("https", sslSocketFactory) 
                .build(); 

        // now, we create connection-manager using our Registry. 
        //      -- allows multi-threaded use 
        PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager( socketFactoryRegistry); 
        connMgr.setMaxTotal(200); 
        connMgr.setDefaultMaxPerRoute(100); 
        b.setConnectionManager( connMgr); 

        // finally, build the HttpClient; 
        //      -- done! 
        CloseableHttpClient client = b.build(); 

        return client; 
    } 

}

 

三.使用

    @Autowired 
    private RestOperations restOperations;

 

    @Test 
    public void testHttpGet(){ 
        String url = "https://internal.api.ehaoyao.com/logistics/v1.1/company"; 

        OauthParam param = new OauthParam(); 
        param.setGrantType("client_credentials"); 
        param.setClientId("02bceec105cd4462b2dadd892fdba943"); 
        param.setClientSecret("fa50ffdbbbf9442f8958e1493e7a1b41"); 
        param.setScope("mall"); 
        String token = oauthService.getToken(param); 
        url=url+"?access_token="+token; 

        Map uriVariables = new HashMap(); 
        uriVariables.put("access_token", token); 
        JSONArray result =  restOperations.getForObject(url, JSONArray.class); 
        System.out.println(result.toString()); 
    }

 

 

--------------

学习视频

springboot中使用RestTemplate_第1张图片

 

复制链接,在浏览器打开
tomcat源码解析
https://study.163.com/course/introduction/1209535854.htm

Springmvc源码解析
https://study.163.com/course/introduction/1209536851.htm

dubbo源码解析
https://study.163.com/course/introduction/1209648816.htm

源码悟道tomcat+springmvc解析
https://study.163.com/course/introduction/1209399899.htm

 

 

 

 

 

你可能感兴趣的:(springboot,spring,java开发)