【Java】实现后端请求接口

【Java】实现后端请求接口

  • 【一】使用 HttpURLConnection 实现四种请求方式的示例
    • 【1】Get请求
    • 【2】POST请求
    • 【3】PUT请求
    • 【4】DELETE 请求
    • 【5】汇总工具类,通过传参实现4种请求
  • 【二】HttpClient 实现四种请求方式的示例
    • 【1】GET请求
    • 【2】POST 请求
    • 【3】PUT 请求
    • 【4】DELETE 请求
    • 【5】汇总的工具类

【一】使用 HttpURLConnection 实现四种请求方式的示例

HttpURLConnection 是 Java 标准库中较早提供的 HTTP 请求工具

【1】Get请求

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;public class HttpGetExample {public static String sendGet(String urlStr) throws Exception {// 对 URL 中的中文参数进行编码String encodedUrl = URLEncoder.encode(urlStr, "UTF-8").replaceAll("\\+", "%20");URL url = new URL(encodedUrl);HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setRequestMethod("GET");// 设置请求头,指定接收的字符编码connection.setRequestProperty("Accept-Charset", "UTF-8");int responseCode = connection.getResponseCode();if (responseCode == HttpURLConnection.HTTP_OK) {// 使用 BufferedReader 读取响应内容,并指定字符编码为 UTF-8BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));StringBuilder response = new StringBuilder();String line;while ((line = reader.readLine()) != null) {response.append(line);}reader.close();return response.toString();}return null;}public static void main(String[] args) {try {String url = "http://example.com/api?param=中文参数";String response = sendGet(url);System.out.println(response);} catch (Exception e) {e.printStackTrace();}}
}

【2】POST请求

import java.io.DataOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;public class HttpPostExample {public static String sendPost(String urlStr, String params) throws Exception {URL url = new URL(urlStr);HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setRequestMethod("POST");// 设置请求头,指定字符编码和内容类型connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");connection.setRequestProperty("Accept-Charset", "UTF-8");connection.setDoOutput(true);// 对请求参数进行编码String encodedParams = URLEncoder.encode(params, "UTF-8");DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());outputStream.writeBytes(encodedParams);outputStream.flush();outputStream.close();int responseCode = connection.getResponseCode();if (responseCode == HttpURLConnection.HTTP_OK) {// 使用 BufferedReader 读取响应内容,并指定字符编码为 UTF-8BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));StringBuilder response = new StringBuilder();String line;while ((line = reader.readLine()) != null) {response.append(line);}reader.close();return response.toString();}return null;}public static void main(String[] args) {try {String url = "http://example.com/api";String params = "param=中文参数";String response = sendPost(url, params);System.out.println(response);} catch (Exception e) {e.printStackTrace();}}
}

【3】PUT请求

import java.io.DataOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;public class HttpPutExample {public static String sendPut(String urlStr, String params) throws Exception {URL url = new URL(urlStr);HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setRequestMethod("PUT");// 设置请求头,指定字符编码和内容类型connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");connection.setRequestProperty("Accept-Charset", "UTF-8");connection.setDoOutput(true);// 对请求参数进行编码String encodedParams = URLEncoder.encode(params, "UTF-8");DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());outputStream.writeBytes(encodedParams);outputStream.flush();outputStream.close();int responseCode = connection.getResponseCode();if (responseCode == HttpURLConnection.HTTP_OK) {// 使用 BufferedReader 读取响应内容,并指定字符编码为 UTF-8BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));StringBuilder response = new StringBuilder();String line;while ((line = reader.readLine()) != null) {response.append(line);}reader.close();return response.toString();}return null;}public static void main(String[] args) {try {String url = "http://example.com/api";String params = "param=中文参数";String response = sendPut(url, params);System.out.println(response);} catch (Exception e) {e.printStackTrace();}}
}

【4】DELETE 请求

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;public class HttpDeleteExample {public static String sendDelete(String urlStr) throws Exception {// 对 URL 中的中文参数进行编码String encodedUrl = URLEncoder.encode(urlStr, "UTF-8").replaceAll("\\+", "%20");URL url = new URL(encodedUrl);HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setRequestMethod("DELETE");// 设置请求头,指定接收的字符编码connection.setRequestProperty("Accept-Charset", "UTF-8");int responseCode = connection.getResponseCode();if (responseCode == HttpURLConnection.HTTP_OK) {// 使用 BufferedReader 读取响应内容,并指定字符编码为 UTF-8BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));StringBuilder response = new StringBuilder();String line;while ((line = reader.readLine()) != null) {response.append(line);}reader.close();return response.toString();}return null;}public static void main(String[] args) {try {String url = "http://example.com/api?param=中文参数";String response = sendDelete(url);System.out.println(response);} catch (Exception e) {e.printStackTrace();}}
}

【5】汇总工具类,通过传参实现4种请求

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;public class HttpUtils {public static String sendRequest(String urlStr, String method, String params) {try {URL url;if (method.equalsIgnoreCase("GET") || method.equalsIgnoreCase("DELETE")) {if (params != null) {urlStr += "?" + URLEncoder.encode(params, "UTF-8").replaceAll("\\+", "%20");}url = new URL(urlStr);} else {url = new URL(urlStr);}HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setRequestMethod(method);// 设置请求头,指定字符编码和接收内容的字符编码connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");connection.setRequestProperty("Accept-Charset", "UTF-8");if (method.equalsIgnoreCase("POST") || method.equalsIgnoreCase("PUT")) {connection.setDoOutput(true);if (params != null) {String encodedParams = URLEncoder.encode(params, "UTF-8");DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());outputStream.writeBytes(encodedParams);outputStream.flush();outputStream.close();}}int responseCode = connection.getResponseCode();if (responseCode == HttpURLConnection.HTTP_OK) {// 使用 BufferedReader 读取响应内容,并指定字符编码为 UTF-8BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));StringBuilder response = new StringBuilder();String line;while ((line = reader.readLine()) != null) {response.append(line);}reader.close();return response.toString();}} catch (Exception e) {e.printStackTrace();}return null;}public static void main(String[] args) {String url = "http://example.com/api";String params = "param=中文参数";String getResponse = sendRequest(url, "GET", params);System.out.println("GET Response: " + getResponse);String postResponse = sendRequest(url, "POST", params);System.out.println("POST Response: " + postResponse);String putResponse = sendRequest(url, "PUT", params);System.out.println("PUT Response: " + putResponse);String deleteResponse = sendRequest(url + "?" + params, "DELETE", null);System.out.println("DELETE Response: " + deleteResponse);}
}

【二】HttpClient 实现四种请求方式的示例

HttpClient 是 Java 11 及以上版本引入的新的 HTTP 客户端,使用起来更加简洁和方便。

【1】GET请求

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;public class HttpClientGetExample {public static void main(String[] args) {try {// 创建 HttpClient 实例HttpClient client = HttpClient.newHttpClient();// 构建 GET 请求,指定请求 URLHttpRequest request = HttpRequest.newBuilder().uri(URI.create("https://example.com/api?param=中文参数")).header("Accept-Charset", "UTF-8") // 设置接收响应的字符编码为 UTF-8.GET().build();// 发送请求并获取响应,指定响应体处理方式为按 UTF-8 编码读取字符串HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());System.out.println("Status code: " + response.statusCode());System.out.println("Response body: " + response.body());} catch (IOException | InterruptedException e) {e.printStackTrace();}}
}

【2】POST 请求

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;public class HttpClientPostExample {public static void main(String[] args) {try {// 构建请求体,对中文参数进行编码String param = URLEncoder.encode("中文参数", StandardCharsets.UTF_8);String requestBody = "param=" + param;// 创建 HttpClient 实例HttpClient client = HttpClient.newHttpClient();// 构建 POST 请求,设置请求头的字符编码和内容类型HttpRequest request = HttpRequest.newBuilder().uri(URI.create("https://example.com/api")).header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8").header("Accept-Charset", "UTF-8").POST(HttpRequest.BodyPublishers.ofString(requestBody)).build();// 发送请求并获取响应,指定响应体处理方式为按 UTF-8 编码读取字符串HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());System.out.println("Status code: " + response.statusCode());System.out.println("Response body: " + response.body());} catch (IOException | InterruptedException e) {e.printStackTrace();}}
}

【3】PUT 请求

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;public class HttpClientPutExample {public static void main(String[] args) {try {// 构建请求体,对中文参数进行编码String param = URLEncoder.encode("中文参数", StandardCharsets.UTF_8);String requestBody = "param=" + param;// 创建 HttpClient 实例HttpClient client = HttpClient.newHttpClient();// 构建 PUT 请求,设置请求头的字符编码和内容类型HttpRequest request = HttpRequest.newBuilder().uri(URI.create("https://example.com/api")).header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8").header("Accept-Charset", "UTF-8").PUT(HttpRequest.BodyPublishers.ofString(requestBody)).build();// 发送请求并获取响应,指定响应体处理方式为按 UTF-8 编码读取字符串HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());System.out.println("Status code: " + response.statusCode());System.out.println("Response body: " + response.body());} catch (IOException | InterruptedException e) {e.printStackTrace();}}
}

【4】DELETE 请求

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;public class HttpClientDeleteExample {public static void main(String[] args) {try {// 创建 HttpClient 实例HttpClient client = HttpClient.newHttpClient();// 构建 DELETE 请求,指定请求 URL 和接收响应的字符编码HttpRequest request = HttpRequest.newBuilder().uri(URI.create("https://example.com/api?param=中文参数")).header("Accept-Charset", "UTF-8").DELETE().build();// 发送请求并获取响应,指定响应体处理方式为按 UTF-8 编码读取字符串HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());System.out.println("Status code: " + response.statusCode());System.out.println("Response body: " + response.body());} catch (IOException | InterruptedException e) {e.printStackTrace();}}
}

【5】汇总的工具类

HttpClientUtils 类中的 sendRequest 方法根据传入的 url、method 和 requestBody 构建相应的 HttpRequest 对象并发送请求。对于 GET 和 DELETE 请求,requestBody 可以传入 null;对于 POST 和 PUT 请求,需要传入请求体内容。在 main 方法中演示了如何调用该工具类的方法进行不同类型的请求。

(1)在请求头中设置 Accept-Charset 为 UTF-8,告诉服务器客户端期望接收的字符编码。
(2)对于 POST 和 PUT 请求,使用 URLEncoder 对请求体中的中文参数进行编码,避免发送时出现乱码。
(3)使用 HttpResponse.BodyHandlers.ofString() 接收响应体,默认以 UTF - 8 编码读取字符串。

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;public class HttpClientUtils {private static final HttpClient client = HttpClient.newHttpClient();public static String sendRequest(String url, String method, String requestBody) {try {HttpRequest.Builder requestBuilder = HttpRequest.newBuilder().uri(URI.create(url)).header("Accept-Charset", "UTF-8");switch (method.toUpperCase()) {case "GET":requestBuilder.GET();break;case "POST":if (requestBody != null) {requestBody = URLEncoder.encode(requestBody, StandardCharsets.UTF_8);}requestBuilder.header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8").POST(HttpRequest.BodyPublishers.ofString(requestBody));break;case "PUT":if (requestBody != null) {requestBody = URLEncoder.encode(requestBody, StandardCharsets.UTF_8);}requestBuilder.header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8").PUT(HttpRequest.BodyPublishers.ofString(requestBody));break;case "DELETE":requestBuilder.DELETE();break;default:throw new IllegalArgumentException("Unsupported HTTP method: " + method);}HttpRequest request = requestBuilder.build();HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());return response.body();} catch (IOException | InterruptedException | IllegalArgumentException e) {e.printStackTrace();return null;}}public static void main(String[] args) {String getUrl = "https://example.com/api?param=中文参数";String postUrl = "https://example.com/api";String putUrl = "https://example.com/api";String deleteUrl = "https://example.com/api?param=中文参数";String postBody = "param=中文参数";String putBody = "param=中文参数";System.out.println("GET response: " + sendRequest(getUrl, "GET", null));System.out.println("POST response: " + sendRequest(postUrl, "POST", postBody));System.out.println("PUT response: " + sendRequest(putUrl, "PUT", putBody));System.out.println("DELETE response: " + sendRequest(deleteUrl, "DELETE", null));}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/18485.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

UE求职Demo开发日志#32 优化#1 交互逻辑实现接口、提取Bag和Warehouse的父类

1 定义并实现交互接口 接口定义&#xff1a; // Fill out your copyright notice in the Description page of Project Settings.#pragma once#include "CoreMinimal.h" #include "UObject/Interface.h" #include "MyInterActInterface.generated.h…

DeepSeek 指导手册(入门到精通)

第⼀章&#xff1a;准备篇&#xff08;三分钟上手&#xff09;1.1 三分钟创建你的 AI 伙伴1.2 认识你的 AI 控制台 第二章&#xff1a;基础对话篇&#xff08;像交朋友⼀样学交流&#xff09;2.1 有效提问的五个黄金法则2.2 新手必学魔法指令 第三章&#xff1a;效率飞跃篇&…

Next.js【详解】获取数据(访问接口)

Next.js 中分为 服务端组件 和 客户端组件&#xff0c;内置的获取数据各不相同 服务端组件 方式1 – 使用 fetch export default async function Page() {const data await fetch(https://api.vercel.app/blog)const posts await data.json()return (<ul>{posts.map((…

【kafka系列】生产者

目录 发送流程 1. 流程逻辑分析 阶段一&#xff1a;主线程处理 阶段二&#xff1a;Sender 线程异步发送 核心设计思想 2. 流程 关键点总结 重要参数 一、核心必填参数 二、可靠性相关参数 三、性能优化参数 四、高级配置 五、安全性配置&#xff08;可选&#xff0…

使用Python爬虫实时监控行业新闻案例

目录 背景环境准备请求网页数据解析网页数据定时任务综合代码使用代理IP提升稳定性运行截图与完整代码总结 在互联网时代&#xff0c;新闻的实时性和时效性变得尤为重要。很多行业、技术、商业等领域的新闻都可以为公司或者个人发展提供有价值的信息。如果你有一项需求是要实时…

JAVA安全—Shiro反序列化DNS利用链CC利用链AES动态调试

前言 讲了FastJson反序列化的原理和利用链&#xff0c;今天讲一下Shiro的反序列化利用&#xff0c;这个也是目前比较热门的。 原生态反序列化 我们先来复习一下原生态的反序列化&#xff0c;之前也是讲过的&#xff0c;打开我们写过的serialization_demo。代码也很简单&…

DeepSeek 助力 Vue 开发:打造丝滑的无限滚动(Infinite Scroll)

前言&#xff1a;哈喽&#xff0c;大家好&#xff0c;今天给大家分享一篇文章&#xff01;并提供具体代码帮助大家深入理解&#xff0c;彻底掌握&#xff01;创作不易&#xff0c;如果能帮助到大家或者给大家一些灵感和启发&#xff0c;欢迎收藏关注哦 &#x1f495; 目录 Deep…

计算机视觉:卷积神经网络(CNN)基本概念(二)

接上一篇《计算机视觉&#xff1a;卷积神经网络(CNN)基本概念(一)》 二、图像特征 三、什么是卷积神经网络&#xff1f; 四、什么是灰度图像、灰度值&#xff1f; 灰度图像是只包含亮度信息的图像&#xff0c;没有颜色信息。灰度值&#xff08;Gray Value&#xff09;是指图…

vscode/cursor 写注释时候出现框框解决办法

一、问题描述 用vscode/cursor写注释出现如图的框框&#xff0c;看着十分难受&#xff0c;用pycharm就没有 二、解决办法 以下两种&#xff0c;哪个好用改那个 &#xff08;1&#xff09;Unicode Highlight:Ambiguous Characters Unicode Highlight:Ambiguous Characters &a…

【2.10-2.16学习周报】

文章目录 摘要Abstract一、理论方法介绍1.模糊类增量学习2.Rainbow Memory(RM)2.1多样性感知内存更新2.2通过数据增强增强样本多样性(DA) 二、实验1.实验概况2.RM核心代码3.实验结果 总结 摘要 本博客概述了文章《Rainbow Memory: Continual Learning with a Memory of Divers…

ABP - 事件总线之分布式事件总线

ABP - 事件总线之分布式事件总线 1. 分布式事件总线的集成1.2 基于 RabbitMQ 的分布式事件总线 2. 分布式事件总线的使用2.1 发布2.2 订阅2.3 事务和异常处理 3. 自己扩展的分布式事件总线实现 事件总线可以实现代码逻辑的解耦&#xff0c;使代码模块之间功能职责更清晰。而分布…

Zotero7 从下载到安装

Zotero7 从下载到安装 目录 Zotero7 从下载到安装下载UPDATE2025.2.16 解决翻译api异常的问题 下载 首先贴一下可用的链接 github官方仓库&#xff1a;https://github.com/zotero/zotero中文社区&#xff1a;https://zotero-chinese.com/官网下载页&#xff1a;https://www.z…

typecho快速发布文章

typecho_Pytools typecho_Pytools工具由python编写&#xff0c;可以快速批量的在本地发布文章&#xff0c;不需要登陆后台粘贴md文件内容&#xff0c;同时此工具还能查看最新的评论消息。… 开源地址: GitHub Gitee 使用教学&#xff1a;B站 一、主要功能 所有操作不用登陆博…

Redis7——基础篇(一)

前言&#xff1a;此篇文章系本人学习过程中记录下来的笔记&#xff0c;里面难免会有不少欠缺的地方&#xff0c;诚心期待大家多多给予指教。 基础篇&#xff1a; Redis&#xff08;一&#xff09; 一、Redis定义 官网地址&#xff1a;Redis - The Real-time Data Platform R…

K8s组件

一、Kubernetes 集群架构组件 K8S 是属于主从设备模型&#xff08;Master-Slave 架构&#xff09;&#xff0c;即有 Master 节点负责集群的调度、管理和运维&#xff0c;Slave 节点是集群中的运算工作负载节点。 主节点一般被称为 Master 节点&#xff0c;master节点上有 apis…

草图绘制技巧

1、点击菜单栏文件–》新建–》左下角高级新手切换–》零件&#xff1b; 2、槽口&#xff1a;直槽口&#xff0c;中心点槽口&#xff0c;三点源槽口&#xff0c;中心点圆弧槽口&#xff1b; 3、草图的约束&#xff1a;需要按住ctrl键&#xff0c;选中两个草图&#xff0c;然后…

一款基于若依的wms系统

Wms-Ruoyi-仓库库存管理 若依wms是一套基于若依的wms仓库管理系统&#xff0c;支持lodop和网页打印入库单、出库单。毫无保留给个人及企业免费使用。 前端采用Vue、Element UI。后端采用Spring Boot、Spring Security、Redis & Jwt。权限认证使用Jwt&#xff0c;支持多终…

AWS transit gateway 的作用

说白了,就是根据需要,来起到桥梁的作用,内部沟通,或者面向internet. 先看一下diagram 图: 最中间的就是transit gateway, 要达到不同vpc 直接通讯的目的: The following is an example of a default transit gateway route table for the attachments shown in the previ…

把 CSV 文件摄入到 Elasticsearch 中 - CSVES

在我们之前的很多文章里&#xff0c;我有讲到这个话题。在今天的文章中&#xff0c;我们就提重谈。我们使用一种新的方法来实现。这是一个基于 golang 的开源项目。项目的源码在 https://github.com/githubesson/csves/。由于这个原始的代码并不支持 basic security 及带有安全…

[操作系统] 基础 IO:理解“文件”与 C 接口

在 Linux 操作系统中&#xff0c;“一切皆文件”这一哲学思想贯穿始终。从基础 IO 学习角度来看&#xff0c;理解“文件”不仅仅意味着了解磁盘上存储的数据&#xff0c;还包括对内核如何管理各种资源的认识。本文将从狭义与广义两个层面对“文件”进行解读&#xff0c;归纳文件…