目录
[5.JWT (JSON Web Token) 在API通信中的作用(简介)](#5.JWT (JSON Web Token) 在API通信中的作用(简介))
=========
1.代码
实现一
java
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class HttpsJsonPostRequest {
/**
* 发送HTTPS POST请求并返回响应内容
* @param urlString 请求URL
* @param jsonInputString JSON请求体
* @return 服务器响应内容
* @throws IOException 如果发生I/O错误
*/
public static String sendJsonPostRequest(String urlString, String jsonInputString) throws IOException {
// 创建URL对象
URL url = new URL(urlString);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
try {
// 设置请求属性
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
connection.setRequestProperty("Accept", "application/json");
connection.setDoOutput(true);
// 设置连接和读取超时(可选)
connection.setConnectTimeout(15000); // 15秒连接超时
connection.setReadTimeout(15000); // 15秒读取超时
// 写入JSON数据到请求体
try (OutputStream os = connection.getOutputStream()) {
byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
// 获取响应码
int responseCode = connection.getResponseCode();
System.out.println("POST Response Code: " + responseCode);
// 读取响应内容
if (responseCode == HttpsURLConnection.HTTP_OK) { // 成功
try (BufferedReader br = new BufferedReader(
new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
StringBuilder response = new StringBuilder();
String responseLine;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine);
}
return response.toString();
}
} else { // 错误响应
try (BufferedReader br = new BufferedReader(
new InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8))) {
StringBuilder errorResponse = new StringBuilder();
String responseLine;
while ((responseLine = br.readLine()) != null) {
errorResponse.append(responseLine);
}
return "Error: " + responseCode + "\n" + errorResponse.toString();
}
}
} finally {
connection.disconnect();
}
}
public static void main(String[] args) {
// 示例使用
String url = "https://api.example.com/endpoint";
String json = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
try {
String response = sendJsonPostRequest(url, json);
System.out.println("Response: " + response);
} catch (IOException e) {
System.err.println("Error sending POST request: " + e.getMessage());
e.printStackTrace();
}
}
}
实现二
・OutputStream是一个字节流,它处理的是原始字节数据,而不是字符数据。String是字符序列,需要根据特定的字符编码(如UTF-8)转换为字节序列才能写入输出流。
・如果尝试直接传入String,编译器会报错,因为OutputStream.write()方法没有接受String参数的重载版本。
如果您想直接写入字符串,可以使用Writer类(如OutputStreamWriter),它是字符流到字节流的桥梁:
java
try(OutputStream os = connection.getOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(os, StandardCharsets.UTF_8)) {
writer.write(jsonInputString); // 这里可以直接写入String
writer.flush();
}
====
2.详细说明
-
创建HTTPS连接 :使用
HttpsURLConnection
建立安全的HTTPS连接 -
设置请求属性:
-
请求方法设置为POST
-
设置Content-Type和Accept头部为application/json
-
启用输出流(
setDoOutput(true)
) -
设置连接和读取超时(可选但推荐)
-
-
写入JSON数据:将JSON字符串转换为UTF-8字节并写入请求体
-
处理响应:
-
检查HTTP响应码
-
对于成功响应(HTTP_OK/200),读取输入流
-
对于错误响应,读取错误流
-
-
资源清理:使用try-with-resources确保正确关闭所有资源
===
3.JWT的OSS的Jar选用【坑】
我们的环境是Java8, JWT使用的OSS的jar的版本过高,造成想定外的错误
9.31版本,【可以正常运行】,但是版本过高,在WAS上发布后,造成服务器上的App自动停止。。。
9.9.3版本是JDK8编译的,可以正常使用,发布到WebSphere上没有问题。
4.不理解的事情
为什么能【可以正常运行】。。。,编译的版本高于JDK8,在java8上运行,不应该报
UnsupportedClassVersionError,
难道还能一部分是 8, 一部分是其它版本。。。。(待确认)
5.JWT (JSON Web Token) 在API通信中的作用(简介)
JWT 在现代应用架构,尤其是基于微服务和前后端分离的架构中,是身份认证 (Authentication) 和安全信息交换 的核心机制。它的主要作用可以概括为:一种无状态的、可自包含的、安全的身份凭证与信息交换格式。
===
下图直观地展示了基于 JWT 的认证与授权流程:

===