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

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);}
}

三、运行截图

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 《C++中的资源管理利器:RAII 技术深度剖析》
  • C++ 文件操作
  • 牛客小白月赛101(栈、差分、调和级数、滑动窗口)
  • NFT Insider #148:The Sandbox 推出 SHIBUYA Y3K 时尚系列,Azuki 进军动漫 NFT 领域
  • 分享一个通用OCR模型GOT-OCR2.0
  • Linux套接字
  • 如何在数据库中备份表:操作指南与注意事项
  • 【busybox记录】【shell指令】timeout
  • MySQL高阶1892-页面推荐2
  • 基于windows的mysql5.7安装配置教程
  • 如何使用Spring Cloud Gateway搭建网关系统
  • VUE面试题(单页应用及其首屏加载速度慢的问题)
  • A. Make All Equal
  • 【C++】C++ STL探索:Priority Queue与仿函数的深入解析
  • Winform管道模拟实现
  • JS 中的深拷贝与浅拷贝
  • 【腾讯Bugly干货分享】从0到1打造直播 App
  • Bytom交易说明(账户管理模式)
  • Docker容器管理
  • golang中接口赋值与方法集
  • java8 Stream Pipelines 浅析
  • Linux gpio口使用方法
  • Mybatis初体验
  • SpringCloud集成分布式事务LCN (一)
  • swift基础之_对象 实例方法 对象方法。
  • 前端设计模式
  • 适配mpvue平台的的微信小程序日历组件mpvue-calendar
  • 为什么要用IPython/Jupyter?
  • 小程序01:wepy框架整合iview webapp UI
  • 异步
  • 异常机制详解
  • 在Unity中实现一个简单的消息管理器
  • ionic异常记录
  • Nginx惊现漏洞 百万网站面临“拖库”风险
  • 浅谈sql中的in与not in,exists与not exists的区别
  • #ubuntu# #git# repository git config --global --add safe.directory
  • (1)虚拟机的安装与使用,linux系统安装
  • (2)STL算法之元素计数
  • (70min)字节暑假实习二面(已挂)
  • (ibm)Java 语言的 XPath API
  • (二)c52学习之旅-简单了解单片机
  • (附源码)springboot 校园学生兼职系统 毕业设计 742122
  • (附源码)springboot猪场管理系统 毕业设计 160901
  • (附源码)ssm码农论坛 毕业设计 231126
  • (附源码)ssm智慧社区管理系统 毕业设计 101635
  • (附源码)计算机毕业设计SSM基于java的云顶博客系统
  • (亲测有效)推荐2024最新的免费漫画软件app,无广告,聚合全网资源!
  • (转载)CentOS查看系统信息|CentOS查看命令
  • .bat批处理(九):替换带有等号=的字符串的子串
  • .Family_物联网
  • .NET 5种线程安全集合
  • .NET 使用 ILRepack 合并多个程序集(替代 ILMerge),避免引入额外的依赖
  • .net/c# memcached 获取所有缓存键(keys)
  • .NET构架之我见
  • /etc/X11/xorg.conf 文件被误改后进不了图形化界面