Springboot integration httpclient code example

Time:2021-7-31

This article mainly introduces the spring boot integration httpclient code example. The example code is introduced in great detail, which has a certain reference value for everyone’s study or work. Friends in need can refer to it

Create httpclientconfig configuration class

@Configuration
@PropertySource(value="classpath:/properties/httpClient.properties")
public class HttpClientConfig {
  @Value("${http.maxTotal}")
  private Integer maxTotal;            // maximum connection

  @Value("${http.defaultMaxPerRoute}")
  private Integer defaultMaxPerRoute;        // Maximum concurrent links

  @Value("${http.connectTimeout}")
  private Integer connectTimeout;          // Maximum time to create link

  @Value("${http.connectionRequestTimeout}") 
  private Integer connectionRequestTimeout;    // Link acquisition timeout

  @Value("${http.socketTimeout}")
  private Integer socketTimeout;           // Maximum data transmission time

  @Value("${http.staleConnectionCheckEnabled}")
  private boolean staleConnectionCheckEnabled;   // Check if the link is available when submitting

  //Define httpclient link pool
  @Bean(name="httpClientConnectionManager")
  public PoolingHttpClientConnectionManager getPoolingHttpClientConnectionManager() {
    PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager();
    manager.setMaxTotal(maxTotal); // Set maximum number of links
    manager.setDefaultMaxPerRoute(defaultMaxPerRoute); // Set the number of concurrent links
    return manager;
  }

  //Define httpclient
  /**
   *Instantiate the connection pool and set the connection pool manager.
   *Here, you need to inject the connection pool manager instantiated above in the form of parameters
   @Qualifier specifies the bean tag for injection
   */
  @Bean(name = "httpClientBuilder")
  public HttpClientBuilder getHttpClientBuilder(@Qualifier("httpClientConnectionManager")PoolingHttpClientConnectionManager httpClientConnectionManager){

    //The construction method in httpclientbuilder is modified by protected, so you can't directly use new to instantiate an httpclientbuilder here. You can use the static method create () provided by httpclientbuilder to obtain the httpclientbuilder object
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    httpClientBuilder.setConnectionManager(httpClientConnectionManager);
    return httpClientBuilder;
  }

  /**
   *Inject connection pool to get httpclient
   * @param httpClientBuilder
   * @return
   */
  @Bean
  public CloseableHttpClient getCloseableHttpClient(@Qualifier("httpClientBuilder") HttpClientBuilder httpClientBuilder){

    return httpClientBuilder.build();
  }

  /**
   *Builder is an internal class of requestconfig
   *Get a builder object through the custom method of requestconfig
   *Set the connection information of the builder
   * @return
   */
  @Bean(name = "builder")
  public RequestConfig.Builder getBuilder(){
    RequestConfig.Builder builder = RequestConfig.custom();
    return builder.setConnectTimeout(connectTimeout)
        .setConnectionRequestTimeout(connectionRequestTimeout)
        .setSocketTimeout(socketTimeout)
        .setStaleConnectionCheckEnabled(staleConnectionCheckEnabled);
  }

  /**
   *Use the builder to build a requestconfig object
   * @param builder
   * @return
   */
  @Bean
  public RequestConfig getRequestConfig(@Qualifier("builder") RequestConfig.Builder builder){
    return builder.build();
  }
}

Create httpclientclose close close configuration class

@Component // to be managed by spring container
public class HttpClientClose extends Thread{
  @Autowired
  private PoolingHttpClientConnectionManager manage;
  private volatile boolean shutdown;  // The switch volatile represents multi-threaded variable data. One thread modifies it and other threads modify it immediately
  
  public HttpClientClose() {
    ///System. Out. Println ("execute the construction method and instantiate the object");
    //Thread start
    this.start();
  }
  
  
  @Override
  public void run() {
    try {
      //If the service is not shut down, execute the thread
      while(!shutdown) {
        synchronized (this) {
          wait(5000);      // Wait 5 seconds
          //System.out.println ("thread starts execution and closes timeout link");
          //Close timed out links
          PoolStats stats = manage.getTotalStats();
          int av = stats.getAvailable();  // Gets the number of threads available
          int pend = stats.getPending();  // Gets the number of blocked threads
          int lea = stats.getLeased();  // Gets the number of links currently in use
          int max = stats.getMax();
          //System.out.println("max/"+max+":  av/"+av+": pend/"+pend+":  lea/"+lea);
          manage.closeExpiredConnections();
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      throw new RuntimeException();
    }

    super.run();
  }
  //Close the thread that cleans up invalid connections
  @Predestroy // execute this method when the container is closed
  public void shutdown() {
    shutdown = true;
    synchronized (this) {
      //System. Out. Println ("close all links!!");
      notifyAll(); // All wake up from waiting. Perform shutdown operation;
    }
  }

Write tool class httpclientservice

@Service
public class HttpClientService {

  @Autowired
  private CloseableHttpClient httpClient;
  @Autowired
  private RequestConfig requestConfig;

  /**
   *Obtain the server data through the given URL address
   *@ param URL server address
   *@ param params encapsulates user parameters
   *@ param charset set set character encoding
   * @return
   */
  public String doGet(String url, Map<String,String> params,String charset) {
    if (StringUtils.isEmpty(charset)) {
      charset = "utf-8";
    }
    //Judge whether there are parameters
    if (params != null) {
      url +="?";
      for (Map.Entry<String,String> entry: params.entrySet()) {
        String key = entry.getKey();
        String value = entry.getValue();
        url += key +"="+value+"&";
      }
      url = url.substring(0,url.length() - 1);
    }
    HttpGet httpGet = new HttpGet(url);
    httpGet.setConfig(requestConfig);
    String result = "";
    try {
      CloseableHttpResponse response = httpClient.execute(httpGet);
      if (response.getStatusLine().getStatusCode() == 200) {
        result = EntityUtils.toString(response.getEntity(),charset);
      }
    } catch (IOException e) {
      e.printStackTrace();
      throw new RuntimeException(e);
    }
    return result;
  }

  public String doGet(String url, Map<String,String> params) {
      return doGet(url,params,null);
  }
  public String doGet(String url) {
    return doGet(url,null,null);
  }

  public <T> T doGet(String url,Class<T> tClass,Map<String,String> map, String charSet){
    String result = doGet(url,map,charSet);
    return ObjectMapperUtil.toObject(result, tClass);
  }

}

Test class:

@SpringBootTest
@RunWith(SpringRunner.class)
public class HttpClientTest {

@Autowired
private HttpClientService httpClientService;
 
@Test 
public void getTest1() {
    //The secondary URL is mapped through nginx plus hosts file. You need to modify the URL before you can use it
    String url = "http://manage.jt.com/web/item/findItemDescById";
    Map<String,String> map = new HashMap<>();
    map.put("itemId","562379");
    String s = httpClientService.doGet(url, map);
    System.out.println(s);

  }

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support developpaer.

Recommended Today

Implementation example of go operation etcd

etcdIt is an open-source, distributed key value pair data storage system, which provides shared configuration, service registration and discovery. This paper mainly introduces the installation and use of etcd. Etcdetcd introduction etcdIt is an open source and highly available distributed key value storage system developed with go language, which can be used to configure sharing […]