Java中用于发送HTTP请求的工具类

 HttpClientUtil是Java中用于发送HTTP请求的工具类,它是基于Apache HttpClient实现的。下面是一个示例代码:


import org.apache.http.HttpEntity;
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.client.utils.URIBuilder;
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.apache.http.NameValuePair;

import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpClientUtil2 {
    /**
     * 发送GET请求
     *
     * @param url 请求URL
     * @return 响应内容
     */
    public static String sendGet(String url) {
        String result = "";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            HttpGet httpGet = new HttpGet(url);
            CloseableHttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity, "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 发送POST请求
     *
     * @param url    请求URL
     * @param params 请求参数
     * @return 响应内容
     */
    public static String sendPost(String url, Map<String, String> params) {
        String result = "";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            HttpPost httpPost = new HttpPost(url);
            if (params != null && params.size() > 0) {
                List<NameValuePair> nameValuePairList = new ArrayList<>();
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    nameValuePairList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePairList, "UTF-8");
                httpPost.setEntity(entity);
            }
            CloseableHttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity, "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 发送带参数的GET请求
     *
     * @param url    请求URL
     * @param params 请求参数
     * @return 响应内容
     */
    public static String sendGetWithParams(String url, Map<String, String> params) {
        String result = "";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            URIBuilder uriBuilder = new URIBuilder(url);
            if (params != null && params.size() > 0) {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    uriBuilder.setParameter(entry.getKey(), entry.getValue());
                }
            }
            URI uri = uriBuilder.build();
            HttpGet httpGet = new HttpGet(uri);
            CloseableHttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity, "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    //这是一个main方法,是程序的入口:
    public static void main(String[] args) {
        // get 请求
        //  String getUrl = "https://gw.alipayobjects.com/os/antvdemo/assets/data/algorithm-category.json";
        // String result = sendGet(getUrl);
        // System.out.println("result = " + result);

        //Post 请求  baocuo
        // String postUrl = "http://localhost:8088/device/factmag/getInfo";
        // Map m = new HashMap();
        // m.put("Authorization","Bearer eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VyX2tleSI6IjNkNmI3ZTFjLTU0ZjgtNGE2NS1iMTY1LTE2NjczYzM1MWIxZiIsInVzZXJuYW1lIjoiYWRtaW4ifQ.AyLfDdY9PjpWInEnaiDUBdJVpStEsP1oheWrxCdRcflzJSWPL2VMFFL2SngTO5S0jrI3uwQBWAsccCOG4hRygg");
        // m.put("facregCode","999999");
        // String s = sendPost(postUrl, m);
        //System.out.println("s = " + s);

       /*String sendGetWithParamsUrl = "http://localhost:9888/boxes2/getprojectinfo";
        Map m = new HashMap();
        m.put("mac","98CC4D111DDE");
        String s = sendGetWithParams(sendGetWithParamsUrl, m);
        System.out.println("s = " + s);*/
    }
}

 

 

上述示例代码中,sendGet方法用于发送GET请求,sendPost方法用于发送POST请求,sendGetWithParams方法用于发送带参数的GET请求。这些方法都使用了相同的HTTP客户端实例,在请求结束后关闭该实例以释放资源。

在使用HttpClientUtil时,需要将Apache HttpClient的相关依赖项添加到项目的构建路径下,例如:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>


posted @ 2023-06-04 19:05  CodeWhisperer001  阅读(140)  评论(0编辑  收藏  举报