Home PC Games Linux Windows Database Network Programming Server Mobile  
  Home \ Programming \ To build Spring RestTemplate use HttpClient4     - System-level alias vs Oracle ADR functionality (Database)

- How to use the Vault secure password storage and API key (Linux)

- Ubuntu 14.04 build Hadoop 2.5.1 standalone and pseudo-distributed environment (32-bit) (Server)

- CentOS How to mount the hard drive (Linux)

- How to set up FTP server on Linux (Server)

- Linux Mint 17 set up the Ruby environment (Linux)

- Process monitoring tools Supervisor start MongoDB (Database)

- Configuring ftp server and nfs server under Linux (Server)

- Oracle delete table space prompted ORA-00604 and ORA-38301 (Database)

- Linux shell script debugging (Linux)

- Java static code analysis tool Infer (Programming)

- Linux, see picture not resolve the problem (Linux)

- Linux run queue process scheduling (Programming)

- Linux system performance analysis and top command ps.pstree Comments (Linux)

- Linux at command (Linux)

- MongoDB3.0.x version of the user authorization profile (stand-alone environment) (Database)

- Python extension module Ganglia 3.1.x (Linux)

- Configure the ASM process on Red Hat Linux 6.5 (Database)

- Redis-2.8.17 installation and configuration process some errors (Linux)

- PXE + Kickstart automatically install CentOS 6.5 (Linux)

  To build Spring RestTemplate use HttpClient4
  Add Date : 2018-11-21      
  Spring RestTemplate brief description

Now REST service has been very popular in our program, you will need to call the REST API, this time there will be many choices, the original point comes with the JDK, further points to use HttpClient, or that if we use this Jersey framework, it also comes with the rest client. However, we project uses SpringMVC, so directly RestTemplate. Use RestTemplate much simpler than using Httpclient, but can also be achieved by means of httpclient RestTemplate.

By using RestTemplate only need to write a few lines of code, you can do a lot of things directly httpclient lines of code, specifically see: https: //spring.io/blog/2009/03/27/rest-in-spring-3- resttemplate

RestTemplate has three constructors:

The default constructor, default SimpleClientHttpRequestFactory, use JDK comes with java.net package for network transmission.
public RestTemplate (ClientHttpRequestFactory requestFactory). Passing a ClientHttpRequestFactory, ClientHttpRequestFactory achieve in Spring there are many, such as HttpComponentsClientHttpRequestFactory, Netty4ClientHttpRequestFactory, the specific code that can be seen here only HttpComponentsClientHttpRequestFactory, need to use HttpClient4.
public RestTemplate (List < HTTPMESSAGECONVERTER < ? >> messageConverters), use of HttpMessageConverter SpringMvc should be very familiar with, RestTemplate default settings will give us a good common HttpMessageConverter, I rarely use to the general constructor.

Here the main discussion by the second constructor to use HttpClient4 for network transmission. Here we look at HttpComponentsClientHttpRequestFactory this class. Take a look at his construction method

/ **
* Create a new instance of the {@code HttpComponentsClientHttpRequestFactory}
* With a default {@link HttpClient}.
* /
public HttpComponentsClientHttpRequestFactory () {
this (HttpClients.createSystem ());

/ **
* Create a new instance of the {@code HttpComponentsClientHttpRequestFactory}
* With the given {@link HttpClient} instance.
* < P> As of Spring Framework 4.0, the given client is expected to be of type
* {@link CloseableHttpClient} (requiring HttpClient 4.3+).
* @param HttpClient the HttpClient instance to use for this request factory
* /
public HttpComponentsClientHttpRequestFactory (HttpClient httpClient) {
Assert.notNull (httpClient, " 'httpClient' must not be null");
Assert.isInstanceOf (CloseableHttpClient.class, httpClient, " 'httpClient' is not of type CloseableHttpClient");
this.httpClient = (CloseableHttpClient) httpClient;
If we do not specify a HttpClient, then, will help us create a default, if we are more frequent calls, then, in order to improve performance, we will consider to build HttpClient use PoolingHttpClientConnectionManager, which will use the time to the second. How to use HttpClient PoolingHttpClientConnectionManager to create it?

Write down the following code to describe how to create RestTemplate by HttpComponentsClientHttpRequestFactory, to facilitate the creation HttpClient code I'll just use my previous article code:

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);

        // Do not check Hostnames, either.
        // - Use SSLConnectionSocketFactory.getDefaultHostnameVerifier (), if you do not 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 < ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder. < ConnectionSocketFactory> 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;

Create and use RestTemplate

        CloseableHttpClient httpClient = HttpClientUtils.acceptsUntrustedCertsHttpClient ();
        HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory (httpClient);
        RestTemplate restTemplate = new RestTemplate (clientHttpRequestFactory);
        String result = restTemplate.getForObject ( "http://www.baidu.com", String.class);
        System.out.println (result);
So the question is, since we are using Spring, it certainly wish him RestTemplate arranged Spring bean to use, HttpClient is thread-safe, he can share in the program, create a Spring bean into exactly. Here is the xml configuration.

   < Bean id = "httpClient" class = "com.hupengcool.util.HttpClientUtils" factory-method = "acceptsUntrustedCertsHttpClient" />

    < Bean id = "clientHttpRequestFactory" class = "org.springframework.http.client.HttpComponentsClientHttpRequestFactory">
        < Constructor-arg ref = "httpClient" />
    < / Bean>

    < Bean id = "restTemplate" class = "org.springframework.web.client.RestTemplate">
        < Constructor-arg ref = "clientHttpRequestFactory" />
    < / Bean>
Spring RestTemplate start using it. . . . .
PS: In addition to the project-related jar Spring kits. We need to add HttpClient4.5, jackson 2.x jar package.
- Proficient in C / C ++ can also find a very good job (Programming)
- Linux system monitoring, top command of the diagnostic tool Detailed (Linux)
- Upload the project to GitHub, synchronous remote repository Github (Linux)
- Simple to install Tor browser to Ubuntu 14.04 and Linux Mint 17 (Linux)
- Linux process management related content (Linux)
- Kibana Apache Password Authentication (Server)
- Close common port to protect server security (Linux)
- Oracle Data Guard LOG_ARCHIVE_DEST_n optional attribute parameters (Database)
- Source code compiled by the installation program under Linux (Linux)
- Based LNMP + uWSGI deploy Django applications (Server)
- MySQL main and backup replication structures (using mysqld_multi) (Database)
- PHP file upload methods exist in the database (Programming)
- Using Java program determines whether it is a leap year (Programming)
- Python basis: os module on the file / directory using methods commonly used functions (Programming)
- DataGuard the MRP can not start to analyze and solve problems (Database)
- Ubuntu 15.04 using the Eclipse 4.4, Java 8 and WTP (Linux)
- MySQL High Availability plan several options (Database)
- Linux Getting Started tutorial: 3D effects and beautify your desktop (Linux)
- Git commands (Linux)
- On the design of Oracle database backup (Database)
  CopyRight 2002-2022 newfreesoft.com, All Rights Reserved.