当前位置:

首页 > 编程开发 > Java HttpClient怎么使用

Java HttpClient怎么使用

1、导入依赖org.apache.httpcomponentshttpclient4.5.3com.alibabafastjson1.2.58org.apache.httpcomponentshttpmime4.5.3org.apache.httpcomponentshttpcore4.4.13org.slf4jslf4j-api1.7.72、使用工具类该工具类将get请求和post请求当中几种传参方式都写了,其中有get地址栏传参、get的params传参、post的params传参、post的json

本文目录

    1、导入依赖

    
        org.apache.httpcomponents
        httpclient
        4.5.3
    
    
    
        com.alibaba
        fastjson
        1.2.58
    
    
     
         org.apache.httpcomponents
         httpmime
         4.5.3
     
    
     
         org.apache.httpcomponents
         httpcore
         4.4.13
     
     
    
        org.slf4j
        slf4j-api
        1.7.7
    

    2、使用工具类

    该工具类将get请求和post请求当中几种传参方式都写了,其中有get地址栏传参、get的params传参、post的params传参、post的json传参。

    import com.alibaba.fastjson.JSONObject;
    import org.apache.http.Consts;
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpStatus;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.ClientProtocolException;
    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.client.utils.URIBuilder;
    import org.apache.http.entity.ContentType;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.entity.mime.HttpMultipartMode;
    import org.apache.http.entity.mime.MultipartEntityBuilder;
    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.*;
    import java.net.URI;
    import java.net.URISyntaxException;
    import java.nio.charset.Charset;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    
    public class HttpClientUtil {
    
        private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
    
        private static final int DEFULT_TIMEOUT = 30 * 1000;//默认超时时间20秒
    
        /**
         * 可以访问  http://localhost:9005/yzhwsj/addPersonal/1/2 这样的接口
         * @param url
         * @param headers
         * @param urlParam
         * @param timeout
         * @return
         */
        private static String doUrlGet(String url, Map headers, List urlParam, Integer timeout) {
            //创建httpClient对象
            CloseableHttpClient httpClient = HttpClients.createDefault();
            String resultString = null;
            CloseableHttpResponse response = null;
            try {
                //创建uri
                if (urlParam != null){
                    for (String param : urlParam) {
                        url = url + "/" + param;
                    }
                }
                //创建hTTP get请求
                HttpGet httpGet = new HttpGet(url);
                //设置超时时间
                int timeoutTmp = DEFULT_TIMEOUT;
                if (timeout != null) {
                    timeoutTmp = timeout;
                }
                RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutTmp)
                        .setConnectionRequestTimeout(timeoutTmp).setSocketTimeout(timeoutTmp).build();
                httpGet.setConfig(requestConfig);
                //设置头信息
                if (null != headers) {
                    for (String key : headers.keySet()) {
                        httpGet.setHeader(key, headers.get(key));
                    }
                }
                //执行请求
                response = httpClient.execute(httpGet);
                if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
                    resultString = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
                }
            } catch (IOException e) {
                logger.error("http调用异常" + e.toString(), e);
            } finally {
                try {
                    if (null != response) {
                        response.close();
                    }
                } catch (IOException e) {
                    logger.error("response关闭异常" + e.toString(), e);
                }
                try {
                    if (null != httpClient) {
                        httpClient.close();
                    }
                } catch (IOException e) {
                    logger.error("httpClient关闭异常" + e.toString(), e);
                }
            }
            return resultString;
        }
    
        /**
         * @param url
         * @param headers
         * @param params
         * @param timeout
         * @return
         */
        private static String doGet(String url, Map headers, Map params, Integer timeout) {
            //创建httpClient对象
            CloseableHttpClient httpClient = HttpClients.createDefault();
            String resultString = null;
            CloseableHttpResponse response = null;
            try {
                // 1.创建uri
                URIBuilder builder = new URIBuilder(url);
                if (params != null) {
                    //uri添加参数
                    for (String key : params.keySet()) {
                        builder.addParameter(key, String.valueOf(params.get(key)));
                    }
                }
                URI uri = builder.build();
                // 2.创建hTTP get请求
                HttpGet httpGet = new HttpGet(uri);
                // 3.设置超时时间
                int timeoutTmp = DEFULT_TIMEOUT;
                if (timeout != null) {
                    timeoutTmp = timeout;
                }
                RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutTmp)
                        .setConnectionRequestTimeout(timeoutTmp).setSocketTimeout(timeoutTmp).build();
                httpGet.setConfig(requestConfig);
                // 4.设置头信息
                if (null != headers) {
                    for (String key : headers.keySet()) {
                        httpGet.setHeader(key, headers.get(key));
                    }
                }
                // 5.执行请求
                response = httpClient.execute(httpGet);
                if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
                    resultString = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
                }
            } catch (URISyntaxException e) {
                logger.error("http调用异常" + e.toString(), e);
            } catch (IOException e) {
                logger.error("http调用异常" + e.toString(), e);
    
            } finally {
                try {
                    if (null != response) {
                        response.close();
                    }
                } catch (IOException e) {
                    logger.error("response关闭异常" + e.toString(), e);
                }
                try {
                    if (null != httpClient) {
                        httpClient.close();
                    }
                } catch (IOException e) {
                    logger.error("httpClient关闭异常" + e.toString(), e);
                }
            }
            return resultString;
        }
    
        /**
         * 调用http post请求(json数据)
         *
         * @param url
         * @param headers
         * @param json
         * @return
         */
        public static String doJsonPost(String url, Map headers, JSONObject json, Integer timeout) {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse response = null;
            String resultString = "";
            try {
                // 1.创建http post请求
                HttpPost httpPost = new HttpPost(url);
                // 2.设置超时时间
                int timeoutTmp = DEFULT_TIMEOUT;
                if (timeout != null) {
                    timeoutTmp = timeout;
                }
                RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutTmp)
                        .setConnectionRequestTimeout(timeoutTmp).setSocketTimeout(timeoutTmp).build();
                httpPost.setConfig(requestConfig);
                // 3.设置参数信息
                StringEntity s = new StringEntity(json.toString(), Consts.UTF_8);
                // 发送json数据需要设置的contentType
                s.setContentType("application/json");
                httpPost.setEntity(s);
                // 4.设置头信息
                if (headers != null) {
                    for (String key : headers.keySet()) {
                        httpPost.setHeader(key, headers.get(key));
                    }
                }
                // 5.执行http请求
                response = httpClient.execute(httpPost);
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    resultString = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
                }
            } catch (UnsupportedEncodingException e) {
                logger.error("调用http异常" + e.toString(), e);
            } catch (ClientProtocolException e) {
                logger.error("调用http异常" + e.toString(), e);
            } catch (IOException e) {
                logger.error("调用http异常" + e.toString(), e);
            } finally {
                try {
                    if (null != response) {
                        response.close();
                    }
                } catch (IOException e) {
                    logger.error("关闭response异常" + e.toString(), e);
                }
                try {
                    if (null != httpClient) {
                        httpClient.close();
                    }
                } catch (IOException e) {
                    logger.error("关闭httpClient异常" + e.toString(), e);
                }
            }
            return resultString;
        }
    
        /**
         * 调用http post请求 基础方法
         *
         * @param url     请求的url
         * @param headers 请求头
         * @param params  参数
         * @param timeout 超时时间
         * @return
         */
        public static String doPost(String url, Map headers, Map params, Integer timeout) {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse response = null;
            String resultString = "";
            try {
                // 1.创建http post请求
                HttpPost httpPost = new HttpPost(url);
                // 2.设置超时时间
                int timeoutTmp = DEFULT_TIMEOUT;
                if (timeout != null) {
                    timeoutTmp = timeout;
                }
                RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutTmp)
                        .setConnectionRequestTimeout(timeoutTmp).setSocketTimeout(timeoutTmp).build();
                httpPost.setConfig(requestConfig);
                // 3.设置参数信息
                if (params != null) {
                    List paramList = new ArrayList<>();
                    for (String key : params.keySet()) {
                        paramList.add(new BasicNameValuePair(key, String.valueOf(params.get(key))));
                    }
                    // 模拟表单
                    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, Consts.UTF_8);
                    httpPost.setEntity(entity);
                }
                // 4.设置头信息
                if (headers != null) {
                    for (String key : headers.keySet()) {
                        httpPost.setHeader(key, headers.get(key));
                    }
                }
                // 5.执行http请求
                response = httpClient.execute(httpPost);
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    resultString = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
                }
            } catch (UnsupportedEncodingException e) {
                logger.error("调用http异常" + e.toString(), e);
            } catch (ClientProtocolException e) {
                logger.error("调用http异常" + e.toString(), e);
            } catch (IOException e) {
                logger.error("调用http异常" + e.toString(), e);
            } finally {
                try {
                    if (null != response) {
                        response.close();
                    }
                } catch (IOException e) {
                    logger.error("关闭response异常" + e.toString(), e);
                }
                try {
                    if (null != httpClient) {
                        httpClient.close();
                    }
                } catch (IOException e) {
                    logger.error("关闭httpClient异常" + e.toString(), e);
                }
            }
            return resultString;
        }
        
    	/**
         * 通过httpClient上传文件
         *
         * @param url      请求的URL
         * @param headers  请求头参数
         * @param path     文件路径
         * @param fileName 文件名称
         * @param timeout  超时时间
         * @return
         */
        public static String UploadFileByHttpClient(String url, Map headers, String path, String fileName, Integer timeout) {
            String resultString = "";
            CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse response = null;
            InputStream content = null;
            BufferedReader in = null;
            try {
                // 1.创建http post请求
                HttpPost httpPost = new HttpPost(url);
    
                // 2.设置超时时间
                int timeoutTmp = DEFULT_TIMEOUT;
                if (timeout != null) {
                    timeoutTmp = timeout;
                }
                RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutTmp)
                        .setConnectionRequestTimeout(timeoutTmp).setSocketTimeout(timeoutTmp).build();
                httpPost.setConfig(requestConfig);
    
                // 3.设置参数信息
                // HttpMultipartMode.RFC6532参数的设定是为避免文件名为中文时乱码
                MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
                // 上传文件的路径
                File file = new File(path + File.separator + fileName);
                builder.setCharset(Charset.forName("UTF-8"));
                builder.addBinaryBody("file", file, ContentType.MULTIPART_FORM_DATA, fileName);
                HttpEntity entity = builder.build();
                httpPost.setEntity(entity);
    
                // 4.设置头信息
                if (headers != null) {
                    for (String key : headers.keySet()) {
                        httpPost.setHeader(key, headers.get(key));
                    }
                }
    
                // 5.执行http请求
                response = httpClient.execute(httpPost);
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    resultString = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
                }
            } catch (Exception e) {
                logger.error("上传文件失败:", e);
            } finally {
                try {
                    if (null != httpClient) {
                        httpClient.close();
                    }
                } catch (IOException e) {
                    logger.error("关闭httpClient异常" + e.toString(), e);
                }
                try {
                    if (null != content) {
                        content.close();
                    }
                } catch (IOException e) {
                    logger.error("关闭content异常" + e.toString(), e);
                }
                try {
                    if (null != in) {
                        in.close();
                    }
                } catch (IOException e) {
                    logger.error("关闭in异常" + e.toString(), e);
                }
            }
    
            return resultString;
        }
     }
    
    	/**
         * 通过httpClient批量上传文件
         *
         * @param url     请求的URL
         * @param headers 请求头参数
         * @param params  参数
         * @param paths   文件路径(key文件名称,value路径)
         * @param timeout 超时时间
         * @return
         */
        public static String UploadFilesByHttpClient(String url, Map headers, Map params, Map paths, Integer timeout) {
            String resultString = "";
            CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse response = null;
            InputStream content = null;
            BufferedReader in = null;
            try {
                // 1.创建http post请求
                HttpPost httpPost = new HttpPost(url);
    
                // 2.设置超时时间
                int timeoutTmp = DEFULT_TIMEOUT;
                if (timeout != null) {
                    timeoutTmp = timeout;
                }
                RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutTmp)
                        .setConnectionRequestTimeout(timeoutTmp).setSocketTimeout(timeoutTmp).build();
                httpPost.setConfig(requestConfig);
    
                // 3.设置文件信息
                // HttpMultipartMode.RFC6532参数的设定是为避免文件名为中文时乱码
                MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
                builder.setCharset(Charset.forName("UTF-8"));
                // 上传文件的路径
                for (Map.Entry m : paths.entrySet()) {
                    File file = new File(m.getValue() + File.separator + m.getKey());
                    builder.addBinaryBody("files", file, ContentType.MULTIPART_FORM_DATA, m.getKey());
                }
    
                // 4.设置参数信息
                ContentType contentType = ContentType.create("text/plain", Charset.forName("UTF-8"));
                for (Map.Entry param : params.entrySet()) {
                    builder.addTextBody(param.getKey(), param.getValue(), contentType);
                }
                HttpEntity entity = builder.build();
                httpPost.setEntity(entity);
    
                // 5.设置头信息
                if (headers != null) {
                    for (String key : headers.keySet()) {
                        httpPost.setHeader(key, headers.get(key));
                    }
                }
    
                // 6.执行http请求
                response = httpClient.execute(httpPost);
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    resultString = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
                }
            } catch (Exception e) {
                logger.error("上传文件失败:", e);
            } finally {
                try {
                    if (null != httpClient) {
                        httpClient.close();
                    }
                } catch (IOException e) {
                    logger.error("关闭httpClient异常" + e.toString(), e);
                }
                try {
                    if (null != content) {
                        content.close();
                    }
                } catch (IOException e) {
                    logger.error("关闭content异常" + e.toString(), e);
                }
                try {
                    if (null != in) {
                        in.close();
                    }
                } catch (IOException e) {
                    logger.error("关闭in异常" + e.toString(), e);
                }
            }
    
            return resultString;
        }

    3、扩展

    上面的工具类,方法都携带了token和超时时间,假如接口用不到可以做接口拓展。例如:

    /**
     * 调用http get请求
     *
     * @param url
     * @param params
     * @return
     */
    public static String doGet(String url, Map params) {
        return doGet(url, null, params, null);
    }

    如果涉及到put请求和delete请求,跟上面都差不多,只不过创建请求的时候改为:

    HttpDelete httpDelete = new HttpDelete();
    
    HttpPut httpPut = new HttpPut();
    本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系bd@zhengruan.com
    作者最新文章
    编程开发 Java httpclient
    相关文章 更多
    Java单元测试入门:使用JUnit 5编写第一个测试用例
    Java单元测试入门:使用JUnit 5编写第一个测试用例

    面向初学者的JUnit 5实用入门指南。从测试概念、Maven依赖配置,到手把手编写首个单元测试用例及断言验证,助你掌握Java单元测试的核心流程。

    Java变量未初始化报错解析:局部变量与成员变量默认值差异
    Java变量未初始化报错解析:局部变量与成员变量默认值差异

    深入解析Java中局部变量未初始化编译报错与成员变量自动赋予默认值的机制差异,涵盖JVM内存分配、编译期确定性赋值检查与实际排查修复方案。

    Java获取当前时间并格式化输出:DateTimeFormatter与SimpleDateFormat
    Java获取当前时间并格式化输出:DateTimeFormatter与SimpleDateFormat

    详细讲解在Java中获取当前系统时间并进行格式化输出的两种核心方案:基于Java 8全新日期时间API的DateTimeFormatter与传统遗留的SimpleDateFormat,包含完整代码示例、线程安全机制对比及生产选型建议。

    Java中final与static final常量的定义及初始化规则
    Java中final与static final常量的定义及初始化规则

    深入解析Java中final变量与static final常量的定义、内存语义、初始化时机及合法赋值路径,涵盖编译期常量优化与实战避坑指南。

    Java抽象方法与接口方法的区别及选型建议
    Java抽象方法与接口方法的区别及选型建议

    深入对比Java中抽象类抽象方法与接口方法的语法演进、设计意图及运行期差异,并提供清晰的架构选型决策流程与实战范例。

    Java实现HTTP请求与JSON解析的完整代码示例
    Java实现HTTP请求与JSON解析的完整代码示例

    本文提供Java标准库HttpClient发起HTTP GET/POST请求并结合Jackson进行JSON数据反序列化与序列化的完整代码示例与工程实践指南。

    Java递归出现StackOverflowError的原因分析及栈空间优化方案
    Java递归出现StackOverflowError的原因分析及栈空间优化方案

    详细分析Java递归调用出现StackOverflowError的原因,结合代码说明线程栈、栈帧和递归深度之间的关系,并介绍终止条件排查、迭代改写、减少栈帧开销以及通过-Xss调整JVM栈空间的方法。

    Java空指针异常(NPE)的代码排查与修复实例
    Java空指针异常(NPE)的代码排查与修复实例

    针对Java中常见的NullPointerException(NPE),本文从堆栈日志定位、典型代码触发场景、具体修复代码对比到防御体系进行系统讲解,提供实用且易上手的排查与修复方案。

    selenium上传文件教程本地文件路径设置方法
    selenium上传文件教程本地文件路径设置方法

    深入解析Selenium处理文件上传的技术细节,涵盖标准HTML控件的路径直接注入法与非标准控件的系统级模拟方案,提供Windows与Linux环境下的路径设置最佳实践及常见异常排查。

    大数据开发语言选型:Java对比Scala与Python的优缺点及适用场景
    大数据开发语言选型:Java对比Scala与Python的优缺点及适用场景

    针对大数据工程场景,系统对比Java、Scala与Python在执行性能、生态结合、开发效率和维护成本上的核心差异,给出清晰的架构选型依据与落地方案。

    查看更多
    精品专题 更多
    装机必备
    装机必备

    正软商城装机必备专区,精选办公、浏览器、安全防护、影音播放、压缩解压、设计创作和系统工具等电脑常用正版软件,帮助用户快速完成新电脑软件配置。

    Windows
    Windows

    正软商城Windows软件专区,汇集适用于Windows电脑的办公、设计、安全防护、影音播放、开发工具和系统优化软件,提供软件介绍、系统要求、正版授权及购买下载服务。

    PDF教程
    PDF教程

    正软商城PDF教程频道提供PDF编辑、转换、合并、拆分、压缩及格式处理方法,同时介绍常用PDF软件和工具的使用技巧。

    Mac软件 更多
    讯飞智作 网页版
    讯飞智作 网页版
    Windows/ macOS/ Linux

    讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

    火山引擎 网页版
    火山引擎 网页版
    Windows/ macOS/ Linux

    火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

    Aperty macOS版
    Aperty macOS版
    macOS

    Aperty 是 Skylum 推出的 AI 人像修图软件,支持自然肤质修饰、瑕疵处理、面部与身体调整、预设及批量同步。

    WINDOWS 更多
    讯飞智作 网页版
    讯飞智作 网页版
    Windows/ macOS/ Linux

    讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

    火山引擎 网页版
    火山引擎 网页版
    Windows/ macOS/ Linux

    火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

    PixTV 网页版
    PixTV 网页版
    Windows

    PixTV 是一款在浏览器中使用的 AI 视觉内容创作平台,提供图片、视频、音频、文字生成、AI 分镜、局部重绘、提示词反推和无限画布等工具,适合短剧、漫剧、广告及社交媒体内容制作。