Java sends external network request

Use HttpClient to send network get/post requests to access network resources

1. Add maven dependency

        <!--发送网络请求依赖-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5</version>
        </dependency>

2. Write tool classes

package org.cloud.sonic.agent.tools.http;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpResponseException;
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.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

/**
 * @author Philip Lee
 * @date 2022/9/27 16:09
 * 发送网络请求工具类
 */
public class HttpRequestTool {

    private static final Logger logger = LoggerFactory.getLogger(HttpRequestTool.class);
    /**
     * 处理get方法,带参数的情况直接使用url拼接
     * examp: String url = "http://localhost:8088/getJsonData2?name=jack&age=18";
     * @param url
     * @throws IOException
     */
    public static void get(String url) throws IOException {
        logger.info("一个新Get请求",url);
        //请求参数设置
        RequestConfig requestConfig = RequestConfig.custom()
                //读取目标服务器数据超时时间
                .setSocketTimeout(10000)
                //连接目标服务器超时时间
                .setConnectTimeout(10000)
                //从连接池获取连接的超时时间
                .setConnectionRequestTimeout(10000)
                .build();

        CloseableHttpClient httpClient = null;
        HttpGet request = null;
        CloseableHttpResponse response = null;
        try {
            //创建HttpClient
            httpClient = HttpClients.createDefault();
            //使用url构建get请求
            request = new HttpGet(url);
            //填充请求设置
            request.setConfig(requestConfig);
            //发送请求,得到响应
            response = httpClient.execute(request);

            //获取响应状态码
            int statusCode = response.getStatusLine().getStatusCode();
            //状态码200 正常
            if (statusCode == 200) {
                //解析响应数据
                HttpEntity entity = response.getEntity();
                //字符串格式数据
                String string = EntityUtils.toString(entity, "UTF-8");
                System.out.println("字符串格式:" + string);
                //json格式数据
                JSONObject jsonObject = JSONObject.parseObject(string);
            } else {
                throw new HttpResponseException(statusCode, "响应异常");
            }
        } finally {
            if (response != null) {
                response.close();
            }
            if (request != null) {
                request.releaseConnection();
            }
            if (httpClient != null) {
                httpClient.close();
            }
        }
    }


    /**
     * 处理带参数的post方法
     * @param url
     * @param param
     * @param token 此参数为发送请求时,需要的token数据, 可根据项目实际情况进行选择是否需要
     * @throws Exception
     */
    public static void post(String url, Object param, String token) throws Exception {
        //请求参数设置
        RequestConfig requestConfig = RequestConfig.custom()
                //读取目标服务器数据超时时间
                .setSocketTimeout(10000)
                //连接目标服务器超时时间
                .setConnectTimeout(10000)
                //从连接池获取连接的超时时间
                .setConnectionRequestTimeout(10000)
                .build();

        CloseableHttpClient httpClient = null;
        HttpPost request = null;
        CloseableHttpResponse response = null;
        try {
            //创建HttpClient
            httpClient = HttpClients.createDefault();
            //使用url构建post请求
            request = new HttpPost(url);
            //填充请求设置
            request.setConfig(requestConfig);
            //判断参数类型 可为Map或JSONObject
            if (null != param) {
                String type = param.getClass().toString();
                if (type.contains("JSON")) {
                    StringEntity entity = new StringEntity(param.toString(), "UTF-8");
                    entity.setContentEncoding("UTF-8");
                    entity.setContentType("application/json");
                    //下面这行代码可以根据实际项目情况来决策是否需要
                    request.setHeader("token", ritsToken);
                    request.setEntity(entity);
                } else if (type.contains("Map")) {
                    Map<String, Object> map = (Map) param;
                    List<NameValuePair> pairs = new ArrayList<>();
                    for (Map.Entry<String, Object> entry : map.entrySet()) {
                        pairs.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
                    }
                    UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(pairs, "UTF-8");
                    urlEncodedFormEntity.setContentType("application/x-www-form-urlencoded");
                    request.setEntity(urlEncodedFormEntity);

                } else {
                    throw new Exception("不支持的参数类型");
                }
                response = httpClient.execute(request);

                //获取响应状态码
                int statusCode = response.getStatusLine().getStatusCode();
                //状态码200 正常
                if (statusCode == 200) {
                    //解析响应数据
                    HttpEntity entity = response.getEntity();
                    //字符串格式数据
                    String string = EntityUtils.toString(entity, "UTF-8");
                    //json格式数据
                    JSONObject jsonObject = JSONObject.parseObject(string);
                } else {
                    throw new HttpResponseException(statusCode, "响应异常");
                }
            }
        } finally {
            if (response != null) {
                response.close();
            }
            if (request != null) {
                request.releaseConnection();
            }
            if (httpClient != null) {
                httpClient.close();
            }
        }
    }


}

Guess you like

Origin blog.csdn.net/PhilipJ0303/article/details/127075025