|
5 | 5 | import lombok.Getter; |
6 | 6 | import lombok.extern.slf4j.Slf4j; |
7 | 7 | import okhttp3.*; |
| 8 | +import okio.Buffer; |
8 | 9 |
|
9 | 10 | import java.io.IOException; |
10 | 11 | import java.nio.charset.StandardCharsets; |
@@ -39,26 +40,50 @@ public Response intercept(Chain chain) throws IOException { |
39 | 40 | // 获取当前的时间戳(UTC标准时间戳) |
40 | 41 | long timestamp = System.currentTimeMillis() / 1000; |
41 | 42 |
|
42 | | - // 构造 HTTP-Body,这里需要根据实际情况构造你的请求体 |
43 | | - // 这里示例构造一个空的请求体 |
44 | | - RequestBody requestBody = RequestBody.create("", MediaType.parse("text/plain")); |
| 43 | + // 获取原始的HTTP-Body |
| 44 | + RequestBody originalRequestBody = originalRequest.body(); |
| 45 | + Buffer buffer = new Buffer(); |
| 46 | + if (originalRequestBody != null) { |
| 47 | + originalRequestBody.writeTo(buffer); |
| 48 | + } |
| 49 | + String httpBody = buffer.readUtf8(); |
45 | 50 |
|
46 | 51 | // 计算 X-BC-Signature |
47 | | - String signature = calculateSignature(secretKey, requestBody, timestamp); |
| 52 | + String signature = calculateSignature(secretKey, httpBody, timestamp); |
48 | 53 |
|
49 | 54 | // 创建新的请求,并添加自定义请求头 |
50 | 55 | Request newRequest = originalRequest.newBuilder() |
51 | | - .addHeader(Header.AUTHORIZATION.getValue(), "Bearer " + apiKey) |
52 | | - .addHeader(Header.CONTENT_TYPE.getValue(), ContentType.JSON.getValue()) |
| 56 | + .addHeader("Authorization", "Bearer " + apiKey) |
| 57 | + .addHeader("Content-Type", "application/json") |
53 | 58 | .addHeader("X-BC-Sign-Algo", "MD5") |
54 | 59 | .addHeader("X-BC-Timestamp", String.valueOf(timestamp)) |
55 | 60 | .addHeader("X-BC-Signature", signature) |
56 | | - .method(originalRequest.method(), originalRequest.body()) |
| 61 | + .method(originalRequest.method(), RequestBody.create(MediaType.parse(ContentType.JSON.getValue()), httpBody)) |
57 | 62 | .build(); |
58 | 63 |
|
59 | 64 | return chain.proceed(newRequest); |
60 | 65 | } |
61 | 66 |
|
| 67 | + private String calculateSignature(String secretKey, String httpBody, long timestamp) { |
| 68 | + String toHash = secretKey + httpBody + timestamp; |
| 69 | + return md5(toHash); |
| 70 | + } |
| 71 | + |
| 72 | + private String md5(String s) { |
| 73 | + try { |
| 74 | + MessageDigest digest = MessageDigest.getInstance("MD5"); |
| 75 | + byte[] result = digest.digest(s.getBytes(StandardCharsets.UTF_8)); |
| 76 | + StringBuilder sb = new StringBuilder(); |
| 77 | + for (byte b : result) { |
| 78 | + sb.append(String.format("%02x", b)); |
| 79 | + } |
| 80 | + return sb.toString(); |
| 81 | + } catch (Exception e) { |
| 82 | + log.error("baichuan secret key md5 error", e); |
| 83 | + return ""; |
| 84 | + } |
| 85 | + } |
| 86 | + |
62 | 87 | private String calculateSignature(String secretKey, RequestBody body, long timestamp) { |
63 | 88 | try { |
64 | 89 | String requestBody = bodyToString(body); |
|
0 commit comments