You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

177 lines
6.6 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package com.dsideal.Res.Util;
import com.dsideal.Config.GatewayConfig;
import okhttp3.*;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class HttpClient {
private static final OkHttpClient OK_HTTP_CLIENT = new OkHttpClient.Builder()
.connectTimeout(GatewayConfig.CONNECT_TIMEOUT, TimeUnit.MILLISECONDS)
.readTimeout(GatewayConfig.READ_TIMEOUT, TimeUnit.MILLISECONDS)
.writeTimeout(GatewayConfig.WRITE_TIMEOUT, TimeUnit.MILLISECONDS)
.connectionPool(new ConnectionPool(GatewayConfig.MAX_CONNECTIONS,
GatewayConfig.KEEP_ALIVE_DURATION,
TimeUnit.SECONDS))
.build();
/**
* 发送GET请求
*
* @param url 请求URL
* @param headers 请求头
* @return 响应字符串
*/
public static String get(String url, Map<String, String> headers) {
Request.Builder builder = new Request.Builder().url(url);
// 添加请求头
if (headers != null) {
headers.forEach(builder::addHeader);
}
try (Response response = OK_HTTP_CLIENT.newCall(builder.build()).execute()) {
if (!response.isSuccessful()) {
throw new IOException("请求失败: " + response);
}
ResponseBody body = response.body();
return body != null ? body.string() : null;
} catch (IOException e) {
throw new RuntimeException("GET请求异常: " + url, e);
}
}
/**
* 发送POST请求JSON格式
*
* @param url 请求URL
* @param jsonBody JSON请求体
* @param headers 请求头
* @return 响应字符串
*/
public static String postJson(String url, String jsonBody, Map<String, String> headers) {
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(jsonBody, JSON);
Request.Builder builder = new Request.Builder()
.url(url)
.post(body);
// 添加请求头
if (headers != null) {
headers.forEach(builder::addHeader);
}
try (Response response = OK_HTTP_CLIENT.newCall(builder.build()).execute()) {
if (!response.isSuccessful()) {
throw new IOException("请求失败: " + response);
}
ResponseBody responseBody = response.body();
return responseBody != null ? responseBody.string() : null;
} catch (IOException e) {
throw new RuntimeException("POST请求异常: " + url, e);
}
}
/**
* 发送POST请求表单格式
*
* @param url 请求URL
* @param formData 表单数据
* @param headers 请求头
* @return 响应字符串
*/
public static String postForm(String url, Map<String, String> formData, Map<String, String> headers) {
FormBody.Builder formBuilder = new FormBody.Builder();
// 添加表单数据
if (formData != null) {
formData.forEach(formBuilder::add);
}
Request.Builder builder = new Request.Builder()
.url(url)
.post(formBuilder.build());
// 添加请求头
if (headers != null) {
headers.forEach(builder::addHeader);
}
try (Response response = OK_HTTP_CLIENT.newCall(builder.build()).execute()) {
if (!response.isSuccessful()) {
throw new IOException("请求失败: " + response);
}
ResponseBody responseBody = response.body();
return responseBody != null ? responseBody.string() : null;
} catch (IOException e) {
throw new RuntimeException("POST请求异常: " + url, e);
}
}
/**
* 发送POST请求文件上传
*
* @param url 请求URL
* @param file 文件
* @param fileName 文件名
* @param headers 请求头
* @return 响应字符串
*/
public static String postFile(String url, File file, String fileName, Map<String, String> headers) {
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", fileName,
RequestBody.create(file, MediaType.parse("application/octet-stream")))
.build();
Request.Builder builder = new Request.Builder()
.url(url)
.post(requestBody);
// 添加请求头
if (headers != null) {
headers.forEach(builder::addHeader);
}
try (Response response = OK_HTTP_CLIENT.newCall(builder.build()).execute()) {
if (!response.isSuccessful()) {
throw new IOException("请求失败: " + response);
}
ResponseBody responseBody = response.body();
return responseBody != null ? responseBody.string() : null;
} catch (IOException e) {
throw new RuntimeException("文件上传异常: " + url, e);
}
}
public static void main(String[] args) {
//正常在Controller中获取到此人员的jwt
// String jwtToken =JwtUtil.getPersonJwt(req);
// 模拟这个场景进行测试
String jwtToken = JwtUtil.generateToken(1, "5499644C-4FC7-4194-8BEA-96AB94466FC2", "-1");
System.out.println(jwtToken);
// 设置请求头
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", jwtToken);//我现在测试的这个登录接口其实是不需要JWT的但有可能有的登录接口需要JWT
headers.put("Content-Type", "application/json");
// POST JSON请求示例
String postUrl = "http://ds-base:8001/dsBase/loginPerson/internal/doLogin";
Map<String, String> jsonBody = new HashMap<>();
String user_name="sys1";
String password = "DsideaL4r5t6y7u";
//本系统的密码需要进行RSA处理后进行提交这与登录系统的密码处理方式一致
String rsaPwd = RsaUtils.encryptedDataOnJava(password, RsaUtils.PUBLICKEY);
jsonBody.put("username", user_name);
jsonBody.put("password", rsaPwd);
String postResponse = HttpClient.postForm(postUrl, jsonBody, headers);
System.out.println("POST Response: " + postResponse);
}
}