HttpClient remote call tool class

Article directory

  • foreword
  • 1. HttpClient tool class
  • 2. Use steps
    • 1. Import library

Foreword

Reminder: The current tool class get method cannot pass paging data, you can tamper with it yourself, if not, use the post method haha~~

Reminder: The following is the text of this article, the following case is for reference

1. HttpClient tool class

package org.benben.modules.business.enterprise.utils;

/**
 * @author Zhang Shuai
 * @description
 * @className HttpClient
 * @date 2023/5/24 11:12
 */
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * HttpClient tool class
 */
public class HttpClient {<!-- -->
    private static RequestConfig requestConfig = null;
    static {<!-- -->
        // Set request and transfer timeouts
        requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
    }

    /**
     * Send get request
     *
     * @param url path
     * @return
     */
    public static JSONObject httpGet(String url) {<!-- -->
        // get request returns result
        JSONObject jsonResult = null;
        CloseableHttpClient client = HttpClients.createDefault();
        // send get request
        HttpGet request = new HttpGet(url);

        request.setConfig(requestConfig);
        try {<!-- -->
            CloseableHttpResponse response = client. execute(request);
            // The request was sent successfully and a response was received
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {<!-- -->
                // Read the json string data returned by the server
                HttpEntity entity = response. getEntity();
                String strResult = EntityUtils.toString(entity, "utf-8");
                // convert json string to json object
                jsonResult = JSONObject. parseObject(strResult);
            } else {<!-- -->
            }
        } catch (IOException e) {<!-- -->
            e.printStackTrace();
        } finally {<!-- -->
            request. releaseConnection();
        }
        return jsonResult;
    }

    /**
     * post request transmits json parameters
     *
     * @param url url address
     * @param jsonParam parameter
     * @return
     */
    public static JSONObject httpjsonPost(String url, JSONObject jsonParam) {<!-- -->
        // post request returns result
        CloseableHttpClient httpClient = HttpClients.createDefault();
        JSONObject jsonResult = null;
        HttpPost httpPost = new HttpPost(url);
        // Set request and transfer timeouts
        httpPost.setConfig(requestConfig);
        try {<!-- -->
            if (null != jsonParam) {<!-- -->
                // Solve the Chinese garbled problem
                StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
            }
            CloseableHttpResponse result = httpClient. execute(httpPost);
            // The request was sent successfully and a response was received
            if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {<!-- -->
                String str = "";
                try {<!-- -->
                    // Read the json string data returned by the server
                    str = EntityUtils.toString(result.getEntity(), "utf-8");
                    // convert json string to json object
                    jsonResult = JSONObject. parseObject(str);
                } catch (Exception e) {<!-- -->
                }
            }
        } catch (IOException e) {<!-- -->
            e.printStackTrace();
        } finally {<!-- -->
            httpPost. releaseConnection();
        }
        return jsonResult;
    }

    /**
     * Post request to transmit String parameters For example: name=Jack & amp;sex=1 & amp;type=2
     * Content-type: application/x-www-form-urlencoded
     *
     * @param url url address
     * @param strParam parameter
     * @return
     */
    public static JSONObject httpPost(String url, String strParam) {<!-- -->
        // post request returns result
        CloseableHttpClient httpClient = HttpClients.createDefault();
        JSONObject jsonResult = null;
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        try {<!-- -->
            if (null != strParam) {<!-- -->
                // Solve the Chinese garbled problem
                StringEntity entity = new StringEntity(strParam, "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
            }
            CloseableHttpResponse result = httpClient. execute(httpPost);
            System.out.println(result);
            // The request was sent successfully and a response was received
            if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {<!-- -->
                String str = "";
                try {<!-- -->
                    // Read the json string data returned by the server
                    str = EntityUtils.toString(result.getEntity(), "utf-8");
                    // convert json string to json object
                    jsonResult = JSONObject. parseObject(str);
                } catch (Exception e) {<!-- -->
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {<!-- -->
            e.printStackTrace();
        } finally {<!-- -->
            httpPost. releaseConnection();
        }
        return jsonResult;
    }

    /**
     * post request to transmit Map<String, String> parameters [not tested, backup]
     * Content-type: application/x-www-form-urlencoded
     *
     * @param url url address
     * @param params parameter
     * @return
     */
    public static String post(String url, Map<String,String> params){<!-- -->
        HttpPost post = null;
        CloseableHttpResponse response=null;
        try{<!-- -->

            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// // Set the timeout
// httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 2000);
// httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 2000);
            List<NameValuePair> list = new ArrayList<NameValuePair>();

            params.forEach((k,v) ->{<!-- -->
                NameValuePair pair = new BasicNameValuePair(k, v);
                list. add(pair);
            });
            UrlEncodedFormEntity entity=null;
            entity = new UrlEncodedFormEntity(list,"UTF-8");
            post = new HttpPost(url);
            // Construct message header
            post.setHeader("Content-type", "application/json; charset=utf-8");
            post.setHeader("Connection", "Close");
            post.setEntity(entity);
            response = httpClient. execute(post);
            if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){<!-- -->
                HttpEntity httpEntity = response. getEntity();
                String result = EntityUtils.toString(httpEntity);
                return result;
            }else{<!-- -->
                System.out.println("error");
            }
        }
        catch (Exception e){<!-- -->
            e.printStackTrace();
        }finally {<!-- -->
            if(post != null){<!-- -->
                post. releaseConnection();
            }
        }
        return "";
    }


}





2. Steps to use

1. Import library

The code is as follows (example):

 /** success
     * Add address
     * @param map
     * @throws IOException
     * @throws SQLException
     */
    @RequestMapping(value = "/address encryption")
    @ResponseBody
    public Object address encryption(@RequestBody Map<String,Object> map) {<!-- -->
    //address
        String url = "http://127.0.0.1:8083/encr/encryption";
        JSONObject item = new JSONObject();
        //Put into json
        item.put("name", map.get("name"));
        //Array transfer
        List<Integer> idss = (List<Integer>)map.get("economize");
        item.put("economize",String.valueOf(idss));
        item.put("specificlocation",map.get("specificlocation"));
        item.put("phone",map.get("phone"));
        item.put("username",map.get("username"));
        
        JSONObject result = HttpClient.httpjsonPost(url,item);
        System.out.println(result);
        return result;
    }