Introduction and application of HttpClient

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

preface

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:

<dependencies>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.3</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.28</version>
        </dependency>
    </dependencies>

The code is as follows (example):

package com.example.springbootsum.controller;

import com.alibaba.fastjson.JSONObject;
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.net.ConnectException;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

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

    @RequestMapping("/showUsertestHttp")
    @ResponseBody
    public void aaa() throws ConnectException, UnknownHostException {
        Map<String,Object> map = new HashMap<>();
        map.put("aa",11);
        String ss = "";
        JSONObject jsonObject = HttpUtils.doPost(YQS_GOODS_DETAIL, map);
        System.out.println(jsonObject);

    }
}

The code is as follows (example):

package com.example.springbootsum.utils;

import com.alibaba.fastjson.JSONObject;
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.io.*;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.UnknownHostException;
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();
        stringBuffer.append(QUESTION_MARK);
        if (null != map) {
            Iterator iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Object> next = (Map.Entry) iterator.next();
                //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
        stringEntity.setContentType("application/json");
        // Load into post
        post.setEntity(stringEntity);
        post.setHeader("content-type", "application/json;charset=UTF-8");
        HttpResponse execute = null;
        try {
            //implement
            execute = client.execute(post);
            if (execute.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                jsonObject = JSONObject.parseObject(EntityUtils.toString(execute.getEntity()));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

}

Topics: Java Back-end