JavaHTTP请求工具类HTTPUtils
创始人
2025-05-30 00:46:34
0

HTTP 请求工具类 HTTPUtils,其中涉及 HTTP 请求相关的各种操作,关于这些方法详细的介绍可以查看这些博客

💬相关

博客文章《Java发起HTTP请求并解析JSON返回数据》

https://blog.csdn.net/weixin_42077074/article/details/128672130

博客文章《Java发起同步和异步HTTP请求》

https://blog.csdn.net/weixin_42077074/article/details/129601132

博客文章《JavaJSON处理工具类JSONUtils》

https://blog.csdn.net/weixin_42077074/article/details/129364274

HTTP 请求工具类 HTTPUtils 包含的方法

  • disableSslVerification():禁用 SSL 验证
  • addHeadersToRequest():将请求头添加到 HTTP 请求中
  • concatParamsToURL():将请求参数拼接进 URL
  • getResponseContent():发起 HTTP 请求并获取响应内容
  • asyncHttpRequest():异步 HTTP 请求
  • printResponseContent():打印响应内容
  • printJSON():打印 JSON
  • printXML():打印 XML
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;import javax.net.ssl.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;public class HTTPUtils {// 请求头示例public static Map headers = new HashMap() {{// 设置接收内容类型put("Accept", "application/json");// 设置发送内容类型put("Content-Type", "application/json;charset=UTF-8");// 设置字符集put("charset", "UTF-8");// 设置访问者系统引擎版本、浏览器信息的字段信息,此处伪装成用户通过浏览器访问put("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");}};// 禁用 SSL 验证public static void disableSslVerification() {try {// 创建不验证证书链的 TrustManagerTrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {public java.security.cert.X509Certificate[] getAcceptedIssuers() {return null;}public void checkClientTrusted(X509Certificate[] certs, String authType) {}public void checkServerTrusted(X509Certificate[] certs, String authType) {}}};// 安装 TrustManagerSSLContext sc = SSLContext.getInstance("SSL");sc.init(null, trustAllCerts, new java.security.SecureRandom());HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());// 创建验证所有主机名的 HostnameVerifierHostnameVerifier allHostsValid = new HostnameVerifier() {public boolean verify(String hostname, SSLSession session) {return true;}};// 安装 HostnameVerifierHttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (KeyManagementException e) {e.printStackTrace();}}// 将请求头键值对添加到 HTTP 请求中public static void addHeadersToRequest(HttpURLConnection httpConn, Map headers){// headers 是 Map 或 Map 类型的请求头,键与值分别是请求头名与请求头值,有重复同名请求头时将多个值放进数组Set headersSet = headers.entrySet();Iterator it = headersSet.iterator();if (it.hasNext()) { // 请求头键值对不为空// 若值为数组(请求头含有同名重复的)if (it.next().getValue().getClass().isArray()) {for(Map.Entry entry : (Set>)headersSet){for (Object value : entry.getValue()) {httpConn.setRequestProperty(entry.getKey().toString(), value.toString());}}}// 若值不为数组(请求头不含有同名重复的)else {for(Map.Entry entry:(Set>)headersSet){httpConn.setRequestProperty(entry.getKey().toString(), entry.getValue().toString());}}}return ;}// 将请求参数拼接进 URLpublic static String concatParamsToURL(String staticURL, String paramsStr) throws Exception {return staticURL + paramsStr;}public static String concatParamsToURL(String staticURL, Map params) throws Exception {// staticURL 是字符串形式的静态 URL// params 是 Map 或 Map 类型的请求参数,键与值分别是参数名与参数值,URL 有重复同名参数时将多个值放进数组Set paramsSet = params.entrySet();Iterator it = paramsSet.iterator();String strURL = staticURL;if (it.hasNext()) { // 参数键值对不为空int paramIndex = 0;// 若值为数组(URL 含有同名重复参数)if (it.next().getValue().getClass().isArray()) {for (Map.Entry entry : (Set>)paramsSet) {for (Object value : entry.getValue()) {if (paramIndex == 0 && strURL.indexOf("?") == -1) strURL += "?";else strURL += "&";// 为了避免中文乱码等问题,将参数值进行转码再拼接进 URLstrURL += URLEncoder.encode(entry.getKey().toString(), "utf-8") + "=" + URLEncoder.encode(value.toString(), "utf-8");paramIndex++;}}}// 若值不为数组(URL 不含有同名重复参数)else {for (Map.Entry entry : (Set>)paramsSet) {if (paramIndex == 0 && strURL.indexOf("?") == -1) strURL += "?";else strURL += "&";// 为了避免中文乱码等问题,将参数值进行转码再拼接进 URLstrURL += URLEncoder.encode(entry.getKey().toString(), "utf-8") + "=" + URLEncoder.encode(entry.getValue().toString(), "utf-8");paramIndex++;}}}return strURL;}// 发起 HTTP 请求并获取响应内容// 重载 getResponseContent(),相当于参数有默认值public static String getResponseContent(String strURL) throws Exception {return getResponseContent(strURL, "GET", null, null);}public static String getResponseContent(String strURL, String method) throws Exception {return getResponseContent(strURL, method, null, null);}public static String getResponseContent(String strURL, String method, Map headers) throws Exception {return getResponseContent(strURL, method, headers, null);}public static String getResponseContent(String strURL, String method, Map headers, Map params) throws Exception {// strURL 是 String 类型的 URL// method 是 String 类型的请求方法,为 "GET" 或 "POST"// headers 是 Map 或 Map 类型的请求头,键与值分别是请求头名与请求头值,有重复同名请求头时将多个值放进数组// params 是 Map 或 Map 类型的请求参数,键与值分别是参数名与参数值,URL 有重复同名参数时将多个值放进数组// 忽略验证 https 中 SSL 证书disableSslVerification();// GET 方法下,query 参数拼接在 URL 字符串末尾if(method == "GET" && params!=null && !params.isEmpty()){strURL = concatParamsToURL(strURL, params);}URL url = new URL(strURL);HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();httpConn.setRequestMethod(method);// 添加 HTTP 请求头addHeadersToRequest(httpConn, headers);// 请求时是否使用缓存httpConn.setUseCaches(false);// POST 方法请求必须设置下面两项// 设置是否从 HttpUrlConnection 的对象写httpConn.setDoOutput(true);// 设置是否从 HttpUrlConnection 的对象读入httpConn.setDoInput(true);// 此处默认 POST 方法发送的内容就是 JSON 形式的 body 参数,可以自行更改if(method == "POST" && params!=null && !params.isEmpty()){// 发送请求OutputStream out = new DataOutputStream(httpConn.getOutputStream());// getBytes() 作用为根据参数给定的编码方式,将一个字符串转化为一个字节数组out.write(JSON.toJSONString(params).getBytes("UTF-8"));out.flush();}else{//发送请求httpConn.connect();}BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));// 循环读取流String line;StringBuffer buffer = new StringBuffer();while ((line = reader.readLine()) != null) {buffer.append(line);}reader.close();httpConn.disconnect();String res = buffer.toString();// 输出响应内容// outputResponseContent(res, "JSON");return res;}// 异步 HTTP 请求public static CompletableFuture asyncHttpRequest(String strURL, String method, Map headers, Map params) {return CompletableFuture.supplyAsync(() -> {try {return getResponseContent(strURL, method, headers, params);} catch (Exception e) {e.printStackTrace();return null;}});}// 打印响应内容public static void printResponseContent(String responseContent, String accept) throws ParserConfigurationException, IOException, SAXException {// accept 是接收内容类型,如"JSON"、"XML"、"HTML"、"Text"等,此处自定义输出方法switch (accept) {case "JSON":// 解析 JSON 字符串为 JSON 对象JSONObject jsonObj = JSON.parseObject(responseContent);printJSONObj(jsonObj);break;case "XML":// 创建 DocumentBuilderFactory 对象DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();// 创建 DocumentBuilder 对象DocumentBuilder builder = factory.newDocumentBuilder();// 将 XML 解析成 Document 对象Document doc = builder.parse(new InputSource(new StringReader(responseContent)));printXML(doc);break;// 可以根据需要添加其他类型的解析和输出default:System.out.println(responseContent);break;}}// 读取并输出 JSON 对象的键值对(含嵌套)public static void printJSON(JSONObject jsonObj) {if (jsonObj != null) {for (Map.Entry entry : jsonObj.entrySet()) {String key = entry.getKey();Object value = entry.getValue();if (value instanceof JSONObject) {// 嵌套对象System.out.println(key + " = {");printJSON((JSONObject) value);System.out.println("}");} else {// 非嵌套对象System.out.println(key + " = " + value.toString());}}}}public static void printXML(Document doc) {try {// 获取文档根元素Element root = doc.getDocumentElement();// 输出文档根元素名System.out.println("根元素:" + root.getNodeName());// 获取文档中所有子元素NodeList nodeList = root.getChildNodes();// 循环遍历子元素并输出for (int i = 0; i < nodeList.getLength(); i++) {Node node = nodeList.item(i);// 判断节点类型是否为元素节点if (node.getNodeType() == Node.ELEMENT_NODE) {System.out.println("元素:" + node.getNodeName());// 输出节点文本内容System.out.println("文本:" + node.getTextContent());}}} catch (Exception e) {e.printStackTrace();}}}

相关内容

热门资讯

监控摄像头接入GB28181平... 流程简介将监控摄像头的视频在网站和APP中直播,要解决的几个问题是:1&...
Windows10添加群晖磁盘... 在使用群晖NAS时,我们需要通过本地映射的方式把NAS映射成本地的一块磁盘使用。 通过...
protocol buffer... 目录 目录 什么是protocol buffer 1.protobuf 1.1安装  1.2使用...
Fluent中创建监测点 1 概述某些仿真问题,需要创建监测点,用于获取空间定点的数据࿰...
educoder数据结构与算法...                                                   ...
MySQL下载和安装(Wind... 前言:刚换了一台电脑,里面所有东西都需要重新配置,习惯了所...
MFC文件操作  MFC提供了一个文件操作的基类CFile,这个类提供了一个没有缓存的二进制格式的磁盘...
在Word、WPS中插入AxM... 引言 我最近需要写一些文章,在排版时发现AxMath插入的公式竟然会导致行间距异常&#...
有效的括号 一、题目 给定一个只包括 '(',')','{','}'...
【Ctfer训练计划】——(三... 作者名:Demo不是emo  主页面链接:主页传送门 创作初心ÿ...