主要方法:GET、POST、获取接口中的文件流并返回、获取JSONNode(方便获取接口数据中的节点数据)
package com.ruoyi.web.core.netUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
/**
* @author Mr.Gan
* 类描述: 网络请求工具
* createTime: 2024/9/6 10:44
*/
public class ActionUtil {
/**
* @author Mr.Gan
* 描述: post请求
* @param * @param null:
* @return
* @date 9:32 2024/9/6
*/
public String getAction(String url){
try {
// 1. 创建URL对象
URL obj = new URL(encodeChineseCharacters(url));
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 2. 设置为POST请求
con.setRequestMethod("POST");
// 3. 设置请求头
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Content-Type", "application/json; utf-8");
// 允许输出
con.setDoOutput(true);
// 5. 获取响应
int status = con.getResponseCode();
if (status == 200) {
// 读取响应内容
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder content = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
return content.toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* @author Mr.Gan
* 描述: post请求
* @param * @param null:
* @return
* @date 9:32 2024/9/6
*/
public String postAction(String url, String body){
try {
// 1. 创建URL对象
URL obj = new URL(encodeChineseCharacters(url));
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 2. 设置为POST请求
con.setRequestMethod("POST");
// 3. 设置请求头
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Content-Type", "application/json; utf-8");
// 允许输出
con.setDoOutput(true);
// 设置Content-Length
int length = body.getBytes("utf-8").length;
con.setRequestProperty("Content-Length", Integer.toString(length));
// 4. 写入请求体
try (OutputStream os = con.getOutputStream()) {
byte[] input = body.getBytes("utf-8");
os.write(input, 0, input.length);
}
// 5. 获取响应
int status = con.getResponseCode();
if (status == 200) {
// 读取响应内容
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder content = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
return content.toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* @author Mr.Gan
* 描述: 获取文件流
* @param * @param null:
* @return
* @date 10:55 2024/9/6
*/
public void getFile(HttpServletResponse response, String urlData) {
try {
// 编码 URL 参数
String encodedUrl = encodeChineseCharacters(urlData);
// 创建 URL 对象
URL url = new URL(encodedUrl);
// 打开连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法
connection.setRequestMethod("GET");
// 设置请求头
// connection.setRequestProperty("Content-Type", "application/json");
// connection.setRequestProperty("Accept", "application/json");
// connection.setDoOutput(true); // 允许输出
// 获取响应码
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// 读取响应
// byte[] pdfBytes = readFully(connection.getInputStream());
// 设置响应头
// response.setContentType("application/pdf");
// response.setHeader("Content-Disposition", "inline; filename=file.pdf"); // 替换为实际的文件名
// 将字节数组写入响应输出流
OutputStream out = response.getOutputStream();
copyStream(connection.getInputStream(), out);
// out.write(pdfBytes);
out.flush();
out.close();
} else {
System.out.println("Failed : HTTP error code : " + responseCode);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @author Mr.Gan
* 描述: 获取jsonnode
* @param * @param null:
* @return
* @date 10:46 2024/9/6
*/
public JsonNode getJsonNode(String data){
// 创建ObjectMapper对象
ObjectMapper mapper = new ObjectMapper();
try {
JsonNode rootNode = mapper.readTree(data);
return rootNode;
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
private void copyStream(InputStream input, OutputStream output) throws IOException {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
}
private String encodeChineseCharacters(String urlString) {
StringBuilder encodedUrl = new StringBuilder();
for (int i = 0; i < urlString.length(); i++) {
char c = urlString.charAt(i);
if (isChineseCharacterOrSymbol(c)) {
try {
encodedUrl.append(java.net.URLEncoder.encode(String.valueOf(c), StandardCharsets.UTF_8.name()));
} catch (IOException e) {
throw new RuntimeException("Failed to encode character", e);
}
} else {
encodedUrl.append(c);
}
}
return encodedUrl.toString();
}
private boolean isChineseCharacterOrSymbol(char c) {
Character.UnicodeBlock block = Character.UnicodeBlock.of(c);
return block == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
|| block == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
|| block == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
|| block == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
|| block == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT
|| block == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
|| block == Character.UnicodeBlock.GENERAL_PUNCTUATION;
}
}