当前位置: 首页 > 图灵资讯 > 技术篇> Java中用于发送HTTP请求的工具类

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

来源:图灵教育
时间:2023-06-05 09:26:32

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 JhbGciOiJIUzUxMiJ9.J1c2VyX2lkIjoxLCJ1c2VyX2tleSI6IjNkNmI3ZTFJU0ZjgtNGE2NS1iMTY1LTE2NjczYZM1MWIxZZJuYW1leJ1YWRtaWRtaW4ZGGE2NGE2ZJuYifQ.AyLFDY9PjpwinaidbdvpspspspaspasphowsplflSFL2SngFL2SngTOSSUSCCCSSCCCOGhRygg");        // m.put("facregCode","999999");        // String s = sendPost(postUrl, m);        //System.out.println("s = " + s);       /*String sendGetWithParamsUrl = "http://localhost:988/boxes2/getprojectinfo";        Map m = new HashMap();        m.put("mac",“98CC4D11DE”;        String s = sendGetWithParams(sendGetWithParamsUrl, m);        System.out.println("s = " + s);*/    }}

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

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

在上述示例代码中,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>

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

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