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

server/2024/9/23 10:22:47/

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

目录

一、完整代码

二、调用示例

三、运行截图


一、完整代码

java">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;}}
}

二、调用示例

java">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.ppmy.cn/server/120026.html

相关文章

16_Python的迭代器

在Python中,迭代是一个非常重要的概念。迭代通常指的是按照某种顺序逐个访问容器中的元素的行为。如使用for循环遍历取值的过程。 可迭代对象(Iterable) 可迭代对象是任何可以返回一个迭代器的对象。简单来说,它是可以逐一返回其…

spark 面试题

spark 面试题 1、spark 任务如何解决第三方依赖 比如机器学习的包,需要在本地安装?--py-files 添加 py、zip、egg 文件不需要在各个节点安装 2、spark 数据倾斜怎么解决 spark 中数据倾斜指的是 shuffle 过程中出现的数据倾斜,主要是由于…

MySQL索引详解

前言 在数据库管理中,索引是提高数据检索速度的重要工具。MySQL作为流行的关系型数据库管理系统,提供了多种类型的索引来优化查询性能。本文将深入探讨MySQL索引的工作原理、类型、创建方法以及最佳实践。 索引简介 MySQL中的索引是一种数据库对象&am…

OpenAI / GPT-4o:Python 返回结构化 / JSON 输出

在调用 OpenAI(比如:GPT-4o)接口时,希望返回的结果是能够在后续任务中自动化处理的结构化 / JSON 输出。GPT 版本:gpt-4o-2024-08-06,提供了这样的功能。 目标:从非结构化输入到结构化数据&…

在 Mac 上安装双系统会影响性能吗,安装双系统会清除数据吗?

在 Mac 系统安装并使用双系统已经成为了许多用户办公的选择之一,双系统可以让用户在 Mac 上同时运行 Windows 或其他操作系统。然而,许多用户担心这样做会对 Mac 的性能产生影响。 接下来将给大家介绍 Mac 装双系统会影响性能吗,Mac装双系统…

将Java程序打包成EXE程序

Java制作可执行jar 方式一:mainClass与lib分离 1)将Java程序依赖的所有jar都拷贝在lib目录下,并添加到classpath中 2)运行时指定MainClass pom.xml 这个pom.xml生成的jar可双击直接运行,但是因为没有将其依赖的jar…

AJAX(一)HTTP协议(请求响应报文),AJAX发送请求,请求问题处理

文章目录 一、AJAX二、HTTP协议1. 请求报文2. 响应报文 三、AJAX案例准备1. 安装node2. Express搭建服务器3. 安装nodemon实现自动重启 四、AJAX发送请求1. GET请求2. POST请求(1) 配置请求体(2) 配置请求头 3. 响应JSON数据的两种方式(1) 手动,JSON.parse()(2) 设置…

PHP:强大的Web开发语言

PHP:强大的Web开发语言 一、PHP 简介及优势 PHP 的基本概念 PHP(PHP: Hypertext Preprocessor)即 “超文本预处理器”,是一种通用开源脚本语言,最初由 Rasmus Lerdorf 于 1994 年创建。它可以在服务器上执行&#xf…