前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >《历史代码分析》4、发起Http请求

《历史代码分析》4、发起Http请求

作者头像
小码农薛尧
发布于 2025-03-10 04:56:25
发布于 2025-03-10 04:56:25
9100
代码可运行
举报
文章被收录于专栏:小码农薛尧小码农薛尧
运行总次数:0
代码可运行
本系列《历史代码分析》为工作中遇到具有代表性的代码。今天我们讲一下,在方法中发起Http请求,常见的就是调用第三方API,代码如下:
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
package tech.xueyao.utils;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


public class HttpUtils {
    /**
     * get
     *
     * @param host
     * @param path
     * @param headers
     * @param querys
     * @return
     * @throws Exception
     */
    public static HttpResponse doGet(String host, String path,
                                     Map<String, String> headers,
                                     Map<String, String> querys)
            throws Exception {
        HttpClient httpClient = wrapClient(host);
        HttpGet request = new HttpGet(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }
        return httpClient.execute(request);
    }

    /**
     * post form
     *
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @param bodys
     * @return
     * @throws Exception
     */
    public static HttpResponse doPost(String host, String path, String method,
                                      Map<String, String> headers,
                                      Map<String, String> querys,
                                      Map<String, String> bodys)
            throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpPost request = new HttpPost(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (bodys != null) {
            List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();

            for (String key : bodys.keySet()) {
                nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
            }
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
            formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
            request.setEntity(formEntity);
        }

        return httpClient.execute(request);
    }

    /**
     * Post String
     *
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @param body
     * @return
     * @throws Exception
     */
    public static HttpResponse doPost(String host, String path, String method,
                                      Map<String, String> headers,
                                      Map<String, String> querys,
                                      String body)
            throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpPost request = new HttpPost(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (StringUtils.isNotBlank(body)) {
            request.setEntity(new StringEntity(body, "utf-8"));
        }

        return httpClient.execute(request);
    }

    /**
     * Post stream
     *
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @param body
     * @return
     * @throws Exception
     */
    public static HttpResponse doPost(String host, String path, String method,
                                      Map<String, String> headers,
                                      Map<String, String> querys,
                                      byte[] body)
            throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpPost request = new HttpPost(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (body != null) {
            request.setEntity(new ByteArrayEntity(body));
        }

        return httpClient.execute(request);
    }

    /**
     * Put String
     *
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @param body
     * @return
     * @throws Exception
     */
    public static HttpResponse doPut(String host, String path, String method,
                                     Map<String, String> headers,
                                     Map<String, String> querys,
                                     String body)
            throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpPut request = new HttpPut(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (StringUtils.isNotBlank(body)) {
            request.setEntity(new StringEntity(body, "utf-8"));
        }

        return httpClient.execute(request);
    }

    /**
     * Put stream
     *
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @param body
     * @return
     * @throws Exception
     */
    public static HttpResponse doPut(String host, String path, String method,
                                     Map<String, String> headers,
                                     Map<String, String> querys,
                                     byte[] body)
            throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpPut request = new HttpPut(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (body != null) {
            request.setEntity(new ByteArrayEntity(body));
        }

        return httpClient.execute(request);
    }

    /**
     * Delete
     *
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @return
     * @throws Exception
     */
    public static HttpResponse doDelete(String host, String path, String method,
                                        Map<String, String> headers,
                                        Map<String, String> querys)
            throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        return httpClient.execute(request);
    }

    private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
        StringBuilder sbUrl = new StringBuilder();
        sbUrl.append(host);
        if (!StringUtils.isBlank(path)) {
            sbUrl.append(path);
        }
        if (null != querys) {
            StringBuilder sbQuery = new StringBuilder();
            for (Map.Entry<String, String> query : querys.entrySet()) {
                if (0 < sbQuery.length()) {
                    sbQuery.append("&");
                }
                if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
                    sbQuery.append(query.getValue());
                }
                if (!StringUtils.isBlank(query.getKey())) {
                    sbQuery.append(query.getKey());
                    if (!StringUtils.isBlank(query.getValue())) {
                        sbQuery.append("=");
                        sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
                    }
                }
            }
            if (0 < sbQuery.length()) {
                sbUrl.append("?").append(sbQuery);
            }
        }

        return sbUrl.toString();
    }

    private static HttpClient wrapClient(String host) {
        HttpClient httpClient = new DefaultHttpClient();
        if (host.startsWith("https://")) {
            sslClient(httpClient);
        }

        return httpClient;
    }

    private static void sslClient(HttpClient httpClient) {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(X509Certificate[] xcs, String str) {

                }

                public void checkServerTrusted(X509Certificate[] xcs, String str) {

                }
            };
            ctx.init(null, new TrustManager[]{tm}, null);
            SSLSocketFactory ssf = new SSLSocketFactory(ctx);
            ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            ClientConnectionManager ccm = httpClient.getConnectionManager();
            SchemeRegistry registry = ccm.getSchemeRegistry();
            registry.register(new Scheme("https", 443, ssf));
        } catch (KeyManagementException ex) {
            throw new RuntimeException(ex);
        } catch (NoSuchAlgorithmException ex) {
            throw new RuntimeException(ex);
        }
    }
}

此工具类应该是复制网络上的某博主的代码,只能说简单好用,提供了常用的请求方法。但是,目前推荐使用开源的Hutool工具库,它包含许多常用的操作,提高开发效率,内网开发除外。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2025-03-09,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 小码农薛尧 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
百度人脸识别API Java调用
工具类下载http://pan.baidu.com/s/1jIuo0N8 小Demo查询。 1.官网文档必须看 http://ai.baidu.com/docs 2.在管理中心创建应用及查看相关参数
小帅丶
2018/02/08
4.3K0
百度人脸识别API Java调用
http请求工具类 HttpClient4Util
1、依赖 <!-- httpclient --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.3.6</version> </dependency> 2、HttpClient4Util http请求工具类 点击查看代码 import lombok.extern.slf4j.Slf4j; import org.apach
化羽羽
2022/11/12
5490
Java微信支付快速入门&工具类
快速入门 1、微信支付官方在线API入口: https://pay.weixin.qq.com/wiki/doc/api/index.html 2、微信支付能力介绍: http://action.we
斯武丶风晴
2018/03/01
2.6K0
Java发送Http请求(HttpClient)
HttpClient 是Apache HttpComponents 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源。虽然在 JDK 的 java net包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活。HttpClient 是Apache HttpComponents 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。
ha_lydms
2023/08/09
1.1K0
HttpClient上传文件传入MultipartFile类型
通常我们在使用httpclient的时候,一把都是使用get或者postd的方式传输一些数据。在近期的项目中有这样的一个需求,我需要通过httpclient去调用一个写好的文件上传的接口,接口中是使用MultipartFile 来接受文件类型参数的。在这种情况下我们就开辟一个HttpClient中的高级功能了。直接上代码,封装了一个工具类:
一缕82年的清风
2021/12/06
5.5K1
使用 HttpClient 调用 Restful 接口
本文节选自《Netkiller Java 手札》 import java.io.IOException; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.ht
netkiller old
2018/03/05
2.7K0
Java 动手写爬虫: 一、实现一个最简单爬虫
第一篇 准备写个爬虫, 可以怎么搞? 使用场景 先定义一个最简单的使用场景,给你一个url,把这个url中指定的内容爬下来,然后停止 一个待爬去的网址(有个地方指定爬的网址) 如何获取指定的内容(可以配置规则来获取指定的内容) 设计 & 实现 1. 基本数据结构 CrawlMeta.java 一个配置项,包含塞入的 url 和 获取规则 /** * Created by yihui on 2017/6/27. */ @ToString public class CrawlMeta { /*
一灰灰blog
2018/02/06
3.2K0
Java 动手写爬虫: 一、实现一个最简单爬虫
分布式性能测试框架用例方案设想(一)
在近期工作规划中,分布式压测框架提上日程,目前「FunTester」已经具备了一些分布式压测中用到的功能。
FunTester
2021/06/23
7400
Java实现调用HTTP请求的几种常见方式
点击上方“芋道源码”,选择“设为星标” 管她前浪,还是后浪? 能浪的浪,才是好浪! 每天 10:33 更新文章,每天掉亿点点头发... 源码精品专栏 原创 | Java 2021 超神之路,很肝~ 中文详细注释的开源项目 RPC 框架 Dubbo 源码解析 网络应用框架 Netty 源码解析 消息中间件 RocketMQ 源码解析 数据库中间件 Sharding-JDBC 和 MyCAT 源码解析 作业调度中间件 Elastic-Job 源码解析 分布式事务中间件 TCC-Transaction
芋道源码
2022/09/19
6K0
Java实现调用HTTP请求的几种常见方式
java模拟http/https post请求
之前每次代码执行到上述代码的第二行的时候,会等一段时间然后会捕获到Exception异常。
翎野君
2023/05/12
1.2K0
java模拟http/https post请求
UrlEncodedFormEntity
UrlEncodedFormEntity这个类是用来把输入数据编码成合适的内容,下面以注册的时候传递的参数为例:
wust小吴
2019/07/08
2.1K0
Java发送HTTPS请求
上篇文章介绍了 java 发送 http 请求,大家都知道发送http是不安全的 。我也是由于对接了其他企业后总结了一套发送 https的工具。大家网上找方法很多的,但是可不是你粘过来就能用啊,我也是踩过坑的,所以我这个工具,只要粘贴到你们自己项目里就可以用。我的工具跟网上没什么区别,唯一的区别是我亲身实战过,把需要注意的细节列出来,不让大家浪费时间。
胖虎
2019/06/26
5.4K0
OkHttp搞定Http请求
当网络出现问题时,OkHttp会自动恢复一般的连接问题;若服务有多个IP地址,当第一个IP请求失败时,OkHttp会交替尝试你配置的其他IP。
鱼找水需要时间
2023/02/16
2.7K0
封装httpClient工具类进行get、post、put、delete的http接口请求,可添加请求头与参数,支持多线程
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/157763.html原文链接:https://javaforall.cn
全栈程序员站长
2022/09/18
2.8K0
日常开发必备神器 HttpUtil 分享(超详细)
最近在工作中需要在后台调用各种上传、下载、以及第三方服务接口,经过研究决定使用 HttpClient,自己封装了一个 HttpClient 工具类,简单轻松的实现get、post、put、delete 以及上传、下载请求,在此分享给大家。
Java极客技术
2022/12/04
3.3K1
Http Cookie的使用
在Java中操作Cookie通常涉及到HttpServletRequest和HttpServletResponse对象。以下是一些常见的操作Cookie的方法:
翰墨飘香
2025/02/06
1150
java 通过HTTP接收json
一: json接收类, 第一个接口为直接传参接收 第二个接口接收json字符串 可以写个HTTP测试类调用测试,也可以postman测试调用,实例方法贴到下面
matinal
2023/10/13
5560
Apache httpClient+Jackson学习笔记
HTMLUnit可以用来做爬虫的。Jsoup比他跟简洁。使用python语言进行爬虫.开箱即用。
全栈程序员站长
2022/06/30
2.6K0
Apache httpClient+Jackson学习笔记
Java发送HTTP 请求
请求http的Demo是个人亲测过,目前该方式已经在线上运行着。因为是http请求,所有发送post 和get 请求的demo都有在下方贴出,包括怎么测试,大家可直接 copy到自己的项目中使用。
胖虎
2019/06/26
2.5K0
Android开发笔记(六十三)HTTP访问的通信方式
输入输出流在java中很常用,从文件读写到内存读写到网络通信都会用到。在之前的《Android开发笔记(三十三)文本文件和图片文件的读写》中,我们学习了文件流FileOutputStream和FileInputStream,以及缓存流BufferedOutputStream和BufferedInputStream。这些输入输出流都继承自InputStream和OutputStream,下面是它们的常用方法: InputStream的常用方法 available : 获取输入流的大小 read : 从输入流中读取数据 close : 关闭输入流 OutputStream的常用方法 write : 往输出流写数据 flush : 刷新输出流 close : 关闭输出流 java在进行http访问操作时,发送数据使用OutputStream,接收数据使用InputStream。如果采用HttpURLConnection,InputStream对象可从HttpURLConnection的getInputStream方法获得;如果采用HttpClient,InputStream对象可从HttpEntity的getContent方法获得。下面是http访问时与InputStream有关的加工操作: 1、从InputStream对象中读取字符串。首先把输入流的数据读到字节流ByteArrayOutputStream,然后调用字节流的toByteArray方法得到字节数组,最后调用String的构造函数根据指定编码从字节数组构造返回字符串; 2、从InputStream对象中读取图像。调用BitmapFactory的decodeStream方法即可返回Bitmap图像数据。 3、从InputStream对象中解压gzip压缩数据。引入GZIPInputStream从输入流构造解压流,然后再从解压流中读取数据。
aqi00
2019/01/18
1.2K0
相关推荐
百度人脸识别API Java调用
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验