Introduction and application of HttpClient

Posted by stanleyg on Tue, 08 Mar 2022 09:47:31 +0100


Tip: Here you can add the general contents to be recorded in this article:

For example, with the continuous development of artificial intelligence, machine learning technology is becoming more and more important. Many people have started learning machine learning. This paper introduces the basic content of machine learning.

Tip: the following is the main content of this article. The following cases can be used for reference

1, HttpClient

All calls between services in spring cloud use HttpClient. In addition, HttpClient is encapsulated in SolrJ. When calling the saveBean method of SolrTemplate, HttpClient technology is called.

At present, the interface exposed by most projects is Http request, and the data format is JSON format, but webService is still used in some old projects.

Main functions provided by HttpClient

(1) All HTTP methods (GET,POST,PUT,DELETE, etc.) are implemented

(2) Support automatic steering

(3) Support HTTPS protocol

(4) Support proxy server, etc

2, Method of use

Using HttpClient to send a request and receive a response is very simple. Generally, the following steps are required.

  1. Create an HttpClient object.

  2. Create an instance of the request method and specify the request URL. If you need to send a GET request, create an HttpGet object; If you need to send a POST request, create an HttpPost object.

  3. If you need to send request parameters, you can call the setParams(HttpParams params) method of HttpGet and HttpPost to add request parameters; For HttpPost objects, you can also call setentity (httpentity) method to set request parameters.

  4. Call execute (httpurirequest request request) of HttpClient object to send the request. This method returns an HttpResponse.

  5. Call getAllHeaders(), getHeaders(String name) and other methods of HttpResponse to obtain the response header of the server; Call the getEntity() method of HttpResponse to get the HttpEntity object, which wraps the response content of the server. The program can obtain the response content of the server through this object.

  6. Release the connection. The connection must be released whether or not the execution method is successful

3, Use steps

Import dependency:


The code is as follows (example):

package com.example.springbootsum.controller;

import com.example.springbootsum.utils.HttpUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

 * @Author lx
 * @Date 2022/1/5 9:45
 * @description: 
 * @Version 0.1.0
public class UserHttpController {
    private static final String YQS_GOODS_DETAIL = "http://***/getDetails";

    public void aaa() throws ConnectException, UnknownHostException {
        Map<String,Object> map = new HashMap<>();
        String ss = "";
        JSONObject jsonObject = HttpUtils.doPost(YQS_GOODS_DETAIL, map);


The code is as follows (example):

package com.example.springbootsum.utils;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

 * @Author lx
 * @Date 2022/1/5 9:43
 * @description: 
 * @Version 0.1.0
public class HttpUtils {

    private static final String AND_CODE = "&";
    private static final String EQUAL_CODE = "=";
    private static final String QUESTION_MARK = "?";

    public static JSONObject doPost(String url, Map<String, Object> map) throws UnknownHostException, ConnectException {
        JSONObject jsonObject = null;
        //Equivalent to establishing an http browser (http client)
        HttpClient client = HttpClients.createDefault();
        //Putting URL s into StringBuilder helps string composition
        StringBuilder stringBuffer = new StringBuilder(url);
        StringBuffer sb = new StringBuffer();
        if (null != map) {
            Iterator iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Object> next = (Map.Entry);
                //Composite url
                sb.append(AND_CODE).append(next.getKey()).append(EQUAL_CODE).append(next.getValue() + "");
            String param = sb.substring(1);
            url = stringBuffer.append(param).toString();
        //In fact, httpPost simulates that the browser sends services to other interfaces on the server
        HttpPost post = new HttpPost(url); // Define Post request
        // Construct the simplest string data
        StringEntity stringEntity = new StringEntity(url, "UTF-8");
        // Format content
        // Load into post
        post.setHeader("content-type", "application/json;charset=UTF-8");
        HttpResponse execute = null;
        try {
            execute = client.execute(post);
            if (execute.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                jsonObject = JSONObject.parseObject(EntityUtils.toString(execute.getEntity()));
        } catch (IOException e) {
        return jsonObject;


Topics: Java Back-end