首页 > 编程语言 >Java中用于发送HTTP请求的工具类

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

时间:2023-06-04 19:22:44浏览次数:42  
标签:HTTP Java String entity 发送 result import apache 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>


标签:HTTP,Java,String,entity,发送,result,import,apache,http
From: https://www.cnblogs.com/2324hh/p/17456138.html

相关文章

  • Java中用于发送HTTP请求的工具类
    ​ HttpClientUtil是Java中用于发送HTTP请求的工具类,它是基于ApacheHttpClient实现的。下面是一个示例代码:importorg.apache.http.HttpEntity;importorg.apache.http.client.entity.UrlEncodedFormEntity;importorg.apache.http.client.methods.CloseableHttpResponse;......
  • Java中HttpClientUtil工具类
     HttpClientUtil包含get和post方法。发送HttpPost或HttpGet请求一共三个步骤:1、创建CloseableHttpClient对象,用于执行excute方法2、创建HttpPost或者HttpGet请求对象3、执行请求,判断返回状态,接收响应对象  publicclassHttpClientUtil{/****编码集*/......
  • Java中HttpClientUtil工具类
     HttpClientUtil包含get和post方法。发送HttpPost或HttpGet请求一共三个步骤:1、创建CloseableHttpClient对象,用于执行excute方法2、创建HttpPost或者HttpGet请求对象3、执行请求,判断返回状态,接收响应对象  publicclassHttpClientUtil{/****编码集*/......
  • Java中HttpClientUtil工具类
    ​ HttpClientUtil包含get和post方法。发送HttpPost或HttpGet请求一共三个步骤:1、创建CloseableHttpClient对象,用于执行excute方法2、创建HttpPost或者HttpGet请求对象3、执行请求,判断返回状态,接收响应对象  publicclassHttpClientUtil{/****编码集......
  • Java中HttpClientUtil工具类
    ​ HttpClientUtil包含get和post方法。发送HttpPost或HttpGet请求一共三个步骤:1、创建CloseableHttpClient对象,用于执行excute方法2、创建HttpPost或者HttpGet请求对象3、执行请求,判断返回状态,接收响应对象  publicclassHttpClientUtil{/****编码集......
  • XMLHttpRequest简单介绍
    1.概述XMLHttpRequest(XHR)对象用于与服务器交互,我们通过XMLHttpRequest可以在不刷新页面的情况下请求特定URL获取数据,并且虽然名字叫XMLHttpRequest,但实际上可以用于获取任何类型的数据。2.使用方式XMLHttpRequest的使用主要可以分为如下几步:创建XMLHttpRequest对象建立......
  • haproxy vegeta压测https
     echo"GEThttps://mail.test.com/EWS/Exchange.asmx"|vegetaattack-rate=300-duration=300s-timeout=300s|teeresults.bin|vegetareport如果提示证书不受信任,则将其域名根证书(.cer)放到放到/etc/pki/ca-trust/source/anchors目录下然后运行/bin/update-ca-trust......
  • Docker安装Java, Apache, Redis, Tomcat, Postgresql, SSH
    [color=red]centos安装Supervisor[/color][url]http://www.alphadevx.com/a/455-Installing-Supervisor-and-Superlance-on-CentOS[/url]网络设定[b][color=darkblue]#创建网络brctladdbrbr0iplinksetdevbr0upipaddradd192.168.2.1/24devbr0#创建容器#......
  • Java实现AWS S3 签名 自定义验证
    前言最近在开发文件存储服务,需要符合s3的协议标准,可以直接接入aws-sdk,本文针对sdk发出请求的鉴权信息进行重新组合再签名验证有效性,sdk版本如下<dependency><groupId>software.amazon.awssdk</groupId><artifactId>s3</artifactId>......
  • Druid使用起步—在javaWeb项目中配置监控
    配置druid监控springjdbc代码[url]http://19950603.blog.51cto.com/9921553/1616566[/url]AliDruid连接池与监控配置[url]http://langmnm.iteye.com/blog/2112099[/url]阿里巴巴Druid配置监控官方:[url]https://github.com/alibaba/druid/wiki/%E9%85%8D%E7%BD%AE_StatV......