SpringBoot实战(二十九)发送HTTP/HTTPS请求的五种实现方式【上篇】(HttpURLConnection、HttpClient)

前言:

  • 在日常工作和学习中,有很多地方都需要发送 HTTP/HTTPS 请求,本文介绍了几种常用的实现方式,供大家参考,收藏不迷路。

由于篇幅问题,本篇文章分为上、下两篇,链接如下:

一、五种实现方式对比结果

为了方便大家选择适合自己的实现方式,先展示五种实现方式的对比结果:

实现方式 底层依赖 优点 缺点
HttpURLConnection Java标准库 (java.net) 1、不需要外部依赖
2、能够直接访问java.net.URL类的功能。
1、功能相对有限。
2、需要手动管理很多资源(如打开和关闭连接)
3、缺乏错误处理和重试机制。
HttpClient Apache HttpClient库 1、提供了丰富的功能集。
2、支持HTTP协议的各种特性。
3、可以方便地管理连接池和请求超时
1、需要引入额外的依赖
2、相比其他轻量级库来说可能显得有些笨重。
OkHttp3 OkHttp3库 1、高性能,支持HTTP/2和其他现代特性。
2、易于使用,API设计友好。
3、提供了很好的错误处理和重试策略
1、需要引入外部依赖
2、对于只需要简单请求的应用来说,可能有些过于复杂。
RestTemplate Spring框架 1、集成了Spring框架,便于集成使用
2、提供了方便的方法来发送各种类型的HTTP请求。
3、支持消息转换器,可以方便地处理请求和响应对象。
1、依赖于Spring框架
2、如果不在Spring环境中使用,可能显得冗余。
Hutool Hutool库 (cn.hutool.http) 1、API简单易用
2、提供了丰富的辅助方法。
3、轻量级,可以作为独立的库使用。
1、需要引入额外的依赖
2、相比于专门的HTTP客户端库,可能在某些高级功能上有所欠缺。

二、Demo接口地址

在开始介绍实现方式之前,推荐一个用于 HTTP/HTTPS 测试的网站,超级好用

这个网站提供了各种方式的接口测试,页面如下所示:

在这里插入图片描述

除了模拟基本的请求方式,这个网站还可以模拟以下各种类型的接口响应:

在这里插入图片描述

实现方式一、java.net.HttpURLConnection 实现

1.1 简介

  • java.net.HttpURLConnection 是 Java 标准库中用来发送 HTTP 请求和接收 HTTP 响应的类。不需要额外引入任何依赖,即可实现

HttpURLConnection 预先定义了一些方法,方便开发者自由地控制请求和响应。如:

  • setRequestMethod():设置 GET、POST 等请求方式;
  • setRequestProperty():设置请求参数。
  • getResponseCode():获取请求状态码。
  • ……

1.2 示例代码

HttpURLConnectionExample.java

import java.net.*;
import java.io.*;
 
public class HttpURLConnectionExample {
   
   
 
    private static HttpURLConnection con;
 
    public static void main(String[] args) throws Exception {
   
   
 
        URL url = new URL("https://www.example.com");
        con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");
 
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer content = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
   
   
            content.append(inputLine);
        }
        in.close();
        con.disconnect();
 
        System.out.println(content.toString());
    }
}

1.3 执行结果

在这里插入图片描述

1.4 补充:工具类(选配)

HttpUtil.java

import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HttpUtil {
   
   

    //MIME部分文件类型对照表
    private static final Map<String, String> FILE_TYPE = new HashMap<>();

    static {
   
   
        FILE_TYPE.put(".jpeg", "image/jpeg");
        FILE_TYPE.put(".jpg", "image/jpg");
        FILE_TYPE.put(".png", "image/png");
        FILE_TYPE.put(".bmp", "image/bmp");
        FILE_TYPE.put(".gif", "image/gif");
        FILE_TYPE.put(".mp4", "video/mp4");
        FILE_TYPE.put(".txt", "text/plain");
        FILE_TYPE.put(".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        FILE_TYPE.put(".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        FILE_TYPE.put(".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation");
        FILE_TYPE.put(".pdf", "application/pdf");
    }

    /**
     * GET请求
     */
    public static String doGet(String url, Map<String, String> params, Map<String, String> headers) {
   
   
        BufferedReader reader = null;
        try {
   
   
            //1、拼接url
            StringBuffer stringBuffer = new StringBuffer(url);
            if (params != null && !params.isEmpty()) {
   
   
                stringBuffer.append("?");
                for (Map.Entry<String, String> entry : params.entrySet()) {
   
   
                    stringBuffer.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
                }
                stringBuffer.deleteCharAt(stringBuffer.length() - 1);
            }
            URL testUrl = new URL(stringBuffer.toString());

            //2、建立链接
            HttpURLConnection conn = (HttpURLConnection) testUrl.openConnection();
            conn.setConnectTimeout(3000); //设置连接超时
            conn.setReadTimeout(3000); //设置读取响应超时
            if (headers != null && !headers.isEmpty()) {
   
   
                for (Map.Entry<String, String> entry : headers.entrySet()) {
   
   
                    conn.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }

            // 3、读取响应
            InputStream inputStream = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(inputStream));
            String line = reader.readLine();
            StringBuffer response = new StringBuffer();
            while (line != null) {
   
   
                response.append(line);
                line = reader.readLine();
                if (line != null) {
   
   
                    response.append("\n");
                }
            }
            reader.close();
            return response.toString();

        } catch (Exception e) {
   
   
            e.printStackTrace();
        } finally {
   
   
            if (reader != null) {
   
   
                try {
   
   
                    reader.close();
                } catch (IOException e) {
   
   
                    System.out.println("输入流关闭失败");
                }
            }
        }
        return null;
    }

    /**
     * POST请求,FORM传参
     */
    public static String doPostByForm(String urlPath, Map<String, String> params, Map<String, String> headers) {
   
   
        OutputStream outputStream = null;
        BufferedReader reader = null;
        try {
   
   
            // 信任所有Hosts(HTTPS专用)
            trustAllHosts();

            // 1、建立连接
            HttpURLConnection conn;
            URL url = new URL(urlPath);
            if (url.getProtocol().equalsIgnoreCase("https")) {
   
   
                HttpsURLConnection httpsConn = (HttpsURLConnection) url.openConnection();
                httpsConn.setHostnameVerifier(DO_NOT_VERIFY);
                conn = httpsConn;
            } else {
   
   
                conn = (HttpURLConnection) url.openConnection();
            }
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);   //允许写入输出流
            conn.setUseCaches(false); //禁用缓存
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            if (headers != null && !headers.isEmpty()) {
   
   
                for (Map.Entry<String, String> entry : headers.entrySet()) {
   
   
                    conn.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }

            // 2、写入请求体
            outputStream = conn.getOutputStream();
            StringBuffer payload = new StringBuffer();
            if (params != null && !params.isEmpty()) {
   
   
                for (Map.Entry<String, String> entry : params.entrySet()) {
   
   
                    payload.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
                }
                payload.deleteCharAt(payload.length() - 1);
            }
            outputStream.write(payload.toString().getBytes());
            outputStream.flush();
            outputStream.close();

            // 3、读取响应
            InputStream inputStream = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(inputStream));
            String line = reader.readLine();
            StringBuffer response = new StringBuffer();
            while (line != null) {
   
   
                response.append(line);
                line = reader.readLine();
                if (line != null) {
   
   
                    response.append("\n");
                }
            }
            reader.close();
            return response.toString();

        } catch (Exception e) {
   
   
            e.printStackTrace();
        } finally {
   
   
            if (outputStream != null) {
   
   
                try {
   
   
                    outputStream.close();
                } catch (IOException e) {
   
   
                    System.out.println("输出流关闭失败");
                }
            }
            if (reader != null) {
   
   
                try {
   
   
                    reader.close();
                } catch (IOException e) {
   
   
                    System.out.println("输入流关闭失败");
                }
            }
        }
        return null;
    }

    /**
     * POST
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不愿放下技术的小赵

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值