当前位置: 首页 > article >正文

Java原生HttpURLConnection实现Get、Post、Put和Delete请求完整工具类分享

这里博主纯手写了一个完整的 HTTP 请求工具类,该工具类支持多种请求方法,包括 GETPOSTPUT 和 DELETE,并且可以选择性地使用身份验证 token。亲测可用,大家可以直接复制并使用这段代码,以便在自己的项目中快速实现 HTTP 请求的功能。

目录

一、完整代码

二、调用示例

三、运行截图


一、完整代码

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUtils {

    public static String doGet(String url) throws Exception {
        return doGet(url, null);
    }

    public static String doGet(String url, String token) throws Exception {
        HttpURLConnection con = createConnection(url, "GET", token);
        return handleResponse(con);
    }

    public static String doPost(String url, String params) throws IOException {
        return doPost(url, null, params);
    }

    public static String doPost(String url, String token, String params) throws IOException {
        HttpURLConnection con = createConnection(url, "POST", token);
        con.setDoOutput(true);

        // 发送 POST 请求
        try (OutputStream os = con.getOutputStream()) {
            byte[] input = params.getBytes("utf-8");
            os.write(input, 0, input.length);
        }

        return handleResponse(con);
    }

    public static String doPut(String url, String params) throws IOException {
        return doPut(url, null, params);
    }

    public static String doPut(String url, String token, String params) throws IOException {
        HttpURLConnection con = createConnection(url, "PUT", token);
        con.setDoOutput(true);

        // 发送 PUT 请求
        try (OutputStream os = con.getOutputStream()) {
            byte[] input = params.getBytes("utf-8");
            os.write(input, 0, input.length);
        }

        return handleResponse(con);
    }

    public static String doDelete(String url) throws IOException {
        return doDelete(url, null);
    }

    public static String doDelete(String url, String token) throws IOException {
        HttpURLConnection con = createConnection(url, "DELETE", token);
        return handleResponse(con);
    }

    private static HttpURLConnection createConnection(String url, String method, String token) throws IOException {
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod(method);
        con.setRequestProperty("Content-Type", "application/json; utf-8");
        con.setRequestProperty("Accept", "application/json");
        if (token != null) {
            con.setRequestProperty("Authorization", "Bearer " + token);
        }
        return con;
    }

    private static String handleResponse(HttpURLConnection con) throws IOException {
        int responseCode = con.getResponseCode();
        StringBuilder response = new StringBuilder();

        if (responseCode == HttpURLConnection.HTTP_OK) {
            try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"))) {
                String line;
                while ((line = in.readLine()) != null) {
                    response.append(line.trim());
                }
            }
            return response.toString();
        } else {
            // 读取错误信息
            try (BufferedReader errorReader = new BufferedReader(new InputStreamReader(con.getErrorStream()))) {
                StringBuilder errorResponse = new StringBuilder();
                String errorLine;
                while ((errorLine = errorReader.readLine()) != null) {
                    errorResponse.append(errorLine);
                }
                System.out.println("接口调用失败:" + errorResponse.toString());
            }
            return null;
        }
    }
}

二、调用示例

import com.alibaba.fastjson.JSONObject;

public class Main {

    public static void main(String[] args) throws Exception {
        String rel = HttpUtils.doGet("http://localhost:9090/api/user/1","e5b086c7-7486-4959-b70f-84fb8970899c");
        System.out.println(rel);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id",2L);
        jsonObject.put("username","李四");
        jsonObject.put("gender","1");
        jsonObject.put("address","上海");
        String rel2 = HttpUtils.doPost("http://localhost:9090/api/user","e5b086c7-7486-4959-b70f-84fb8970899c",jsonObject.toString());
        System.out.println(rel2);
        String rel3 = HttpUtils.doPut("http://localhost:9090/api/user","e5b086c7-7486-4959-b70f-84fb8970899c",jsonObject.toString());
        System.out.println(rel3);
        String rel4 = HttpUtils.doDelete("http://localhost:9090/api/user/1","e5b086c7-7486-4959-b70f-84fb8970899c");
        System.out.println(rel4);
    }
}

三、运行截图


http://www.kler.cn/a/308612.html

相关文章:

  • 编写红绿起爆线指标(附带源码下载)
  • SHELL脚本(Linux)
  • 微服务(二)
  • 树形dp总结
  • MySQL重难点(一)索引
  • NAT网络工作原理和NAT类型
  • 高级I/O知识分享【5种IO模型 || select || poll】
  • c++概念
  • windows启动jar指定jdk路径
  • 网页本地存储
  • 【C++】list 模拟实现
  • Vscode运行Python无法导入自己编写的包的解决方法
  • 后端开发刷题 | 最长上升子序列
  • odoo14 | 报错:Database backup error: Access Denied
  • MyBatis之手动映射
  • SSL认证解说
  • 个人随想-gpt-o1大模型中推理链的一个落地实现
  • Linux学习记录十四----------线程的创建和回收
  • Leetcode—1184. 公交站间的距离【简单】
  • Linux(CentOS8)服务器安装RabbitMQ
  • Python数据分析工具(一):Requests的用法
  • 游戏中的唯一id生成,防止合服id重复
  • 成功激活mac idea 记录
  • Java封装(面向对象)
  • 104.WEB渗透测试-信息收集-FOFA语法(4)
  • 腾讯百度阿里华为常见算法面试题TOP100(4):双指针、哈希、滑动窗口