HttpClient introduction and simple use process

Keywords: Java RESTful http

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 exposed interface of 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. Type of Http request (common)

Meanings and differences of get, put, post and delete

(1) The GET request will send a request for data to the database to obtain information. Like the select operation of the database, the request is only used to query the data, will not modify or add data, and will not affect the content of resources, that is, the request will not have side effects. No matter how many operations are performed, the result is the same.

(2) Unlike GET, a PUT request sends data to the server to change the information. Like the update operation of the database, the request is used to modify the content of the data, but does not increase the type of data. In other words, no matter how many PUT operations are performed, the results are not different.

(3) Similar to the PUT request, the POST request sends data to the server, but the request will change the type of data and other resources. Just like the insert operation of the database, it will create new content. At present, almost all submission operations are requested by POST.

(4) As the name suggests, the delete request is used to delete a resource. The request is like the delete operation of the database.

As mentioned earlier, since both PUT and POST operations send data to the server, what is the difference between the two... POST mainly functions on a set of resources (URL), while PUT mainly functions on a specific resource (url/xxx). Generally speaking, if the URL can be determined on the client, PUT can be used, otherwise POST can be used.

Data request format
To sum up, we can understand it as follows:
(1) POST /url creation
(2) DELETE /url/xxx delete
(3) PUT /url/xxx update
(4) GET /url/xxx view

3. Request type of httpclient

All Http request types are implemented, and the corresponding classes are
HttpGet,HttpPost,HttpDelete,HttpPut

4. Use process of HTTP

(1) Create a war sub module of sms
(2) Import coordinates

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

(3) Test demo, used by native HttpClient

(4) Create a new HttpClientGetTest.java test class to test the get request

public static void main(String[] args) throws IOException {
        //1. Open the browser
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //2. Declare get request
        HttpGet httpGet = new HttpGet("http://www.baidu.com/s?wd=java");
        //3. Send request
        CloseableHttpResponse response = httpClient.execute(httpGet);
        //4. Judgment status code
        if(response.getStatusLine().getStatusCode()==200){
            HttpEntity entity = response.getEntity();
           //Use the tool class EntityUtils to extract the content represented by the entity from the response and convert it into a string
            String string = EntityUtils.toString(entity, "utf-8");
            System.out.println(string);
        }
        //5. Close resources
        response.close();
        httpClient.close();
    }

(5) Create a new httpclientpostest.java test class to test the post request

public static void main(String[] args) throws IOException {
        //1. Open the browser
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //2. Declare get request
        HttpPost httpPost = new HttpPost("https://www.oschina.net/");
        //3. In order to ensure security and prevent malicious attacks, open source China restricts browser access in post requests
        httpPost.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36");
        //4. Judgment status code
        List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
        parameters.add(new BasicNameValuePair("scope", "project"));
        parameters.add(new BasicNameValuePair("q", "java"));

        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters,"UTF-8");

        httpPost.setEntity(formEntity);

        //5. Send request
        CloseableHttpResponse response = httpClient.execute(httpPost);

        if(response.getStatusLine().getStatusCode()==200){
            HttpEntity entity = response.getEntity();
            String string = EntityUtils.toString(entity, "utf-8");
            System.out.println(string);
        }
        //6. Close resources
        response.close();
        httpClient.close();
    }

5. Test and obtain the implementation of operator brand data code
If the custom tool class HttpClientUtil can be accessed directly, it can be implemented simply.

//Set request address
HttpClientUtil util=new HttpClientUtil("http://localhost:9101/brand/findAll.do");
//Set request mode
util.get();
//Get return content
String content=util.getContent();
//Print results
System.out.println("content");

Use HttpClientUtil to log in to the access page first
Important: make sure that login and query requests are continuous. With the help of the custom tool class HttpClientUtil

public class HttpClientTest {
    public static void main(String[] args) {
        //Set user name and password
        Map<String, String> map = new HashMap<String,String>();
        map.put("username", "admin");
        map.put("password", "123456");

        //Spring security authentication is required first
        String s1 = HttpClientUtil.doPost("http://localhost:9101/login", map);

        Map<String, String> brand = new HashMap<String,String>();
        brand.put("name", "123456");
        brand.put("firstChar", "T");

        String jsonMap = JSON.toJSONString(brand);
        System.out.println(jsonMap);
        String s2 = HttpClientUtil.doPostJson("http://localhost:9101/brand/add.do", jsonMap);

        //String s2 = HttpClientUtil.doGet("http://localhost:9101/brand/findAll.do");
        System.out.println(s2);
    }
}

Custom tool class source code HttpClientUtil. Note the dependency of the import

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.ParseException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
 * http Request client
 * 
 * @author Administrator
 * 
 */
public class HttpClientUtil {

    public  static HttpClientContext context = null;

    static {
        System.out.println("====================begin");
        context = HttpClientContext.create();
    }

    private String url;
    private Map<String, String> param;
    private int statusCode;
    private String content;
    private String xmlParam;
    private boolean isHttps;

    public boolean isHttps() {
        return isHttps;
    }

    public void setHttps(boolean isHttps) {
        this.isHttps = isHttps;
    }

    public String getXmlParam() {
        return xmlParam;
    }

    public void setXmlParam(String xmlParam) {
        this.xmlParam = xmlParam;
    }

    public HttpClientUtil(String url, Map<String, String> param) {
        this.url = url;
        this.param = param;
    }

    public HttpClientUtil(String url) {
        this.url = url;
    }

    public void setParameter(Map<String, String> map) {
        param = map;
    }

    public void addParameter(String key, String value) {
        if (param == null)
            param = new HashMap<String, String>();
        param.put(key, value);
    }

    public void post() throws ClientProtocolException, IOException {
        HttpPost http = new HttpPost(url);
        setEntity(http);
        execute(http);
    }

    public void put() throws ClientProtocolException, IOException {
        HttpPut http = new HttpPut(url);
        setEntity(http);
        execute(http);
    }

    public void get() throws ClientProtocolException, IOException {
        if (param != null) {
            StringBuilder url = new StringBuilder(this.url);
            boolean isFirst = true;
            for (String key : param.keySet()) {
                if (isFirst)
                    url.append("?");
                else
                    url.append("&");
                url.append(key).append("=").append(param.get(key));
            }
            this.url = url.toString();
        }
        HttpGet http = new HttpGet(url);
        execute(http);
    }

    /**
     * set http post,put param
     */
    private void setEntity(HttpEntityEnclosingRequestBase http) {
        if (param != null) {
            List<NameValuePair> nvps = new LinkedList<NameValuePair>();
            for (String key : param.keySet())
                nvps.add(new BasicNameValuePair(key, param.get(key))); // parameter
            http.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); // Set parameters
        }
        if (xmlParam != null) {
            http.setEntity(new StringEntity(xmlParam, Consts.UTF_8));
        }
    }

    private void execute(HttpUriRequest http) throws ClientProtocolException,
            IOException {
        CloseableHttpClient httpClient = null;
        try {
            if (isHttps) {
                SSLContext sslContext = new SSLContextBuilder()
                        .loadTrustMaterial(null, new TrustStrategy() {
                            // Trust all
                            public boolean isTrusted(X509Certificate[] chain,
                                    String authType)
                                    throws CertificateException {
                                return true;
                            }
                        }).build();
                SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                        sslContext);
                httpClient = HttpClients.custom().setSSLSocketFactory(sslsf)
                        .build();
            } else {
                httpClient = HttpClients.createDefault();
            }
            CloseableHttpResponse response = httpClient.execute(http,context);
            try {
                if (response != null) {
                    if (response.getStatusLine() != null)
                        statusCode = response.getStatusLine().getStatusCode();
                    HttpEntity entity = response.getEntity();
                    // Response content
                    content = EntityUtils.toString(entity, Consts.UTF_8);
                }
            } finally {
                response.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            httpClient.close();
        }
    }
    
    public int getStatusCode() {
        return statusCode;
    }

    public String getContent() throws ParseException, IOException {
        return content;
    }
}

Posted by paulg on Mon, 20 Sep 2021 02:33:50 -0700