Skip to content

Commit

Permalink
fix: use okhttp3 to fix bad request error
Browse files Browse the repository at this point in the history
  • Loading branch information
hank9999 committed Jul 23, 2024
1 parent 866e184 commit 368fdd1
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 90 deletions.
5 changes: 5 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -116,5 +116,10 @@
<artifactId>configurate-yaml</artifactId>
<version>4.2.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.12.0</version>
</dependency>
</dependencies>
</project>
Original file line number Diff line number Diff line change
@@ -1,34 +1,33 @@
package com.github.hank9999.useblessingskin.shared;

import okhttp3.*;
import okhttp3.Response;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

final public class httpMethods {
private static final OkHttpClient client = new OkHttpClient();

public static String getUrl(String url) throws Exception {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", "UseBlessingSkinPlugin/1.0");
con.setConnectTimeout(10000);
con.setReadTimeout(10000);
con.setDoOutput(true);
int responseCode = con.getResponseCode();
if (responseCode == 404 || responseCode == 204) {
return null;
}
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
Request request = new Request.Builder()
.url(url)
.header("User-Agent", "UseBlessingSkinPlugin/1.0")
.build();

while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
try (Response response = client.newCall(request).execute()) {
if (response.code() == 404 || response.code() == 204) {
return null;
}

if (!response.isSuccessful()) {
throw new IOException("HTTP error code: " + response.code() + " | " + response.message());
}

return response.body() != null ? response.body().string() : null;
}
in.close();
return response.toString();
}

public static boolean getPicture(String urlHttp, String path, String picName) throws Exception {
Expand All @@ -54,75 +53,29 @@ public static boolean getPicture(String urlHttp, String path, String picName) th
}

public static String postPic(String urlHttp, String picName, String picPath) throws Exception {

String BOUNDARY = "========7d4a6d158c9";

URL url = new URL(urlHttp);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

// 设置POST请求
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);

// 设置header参数
conn.setRequestProperty("User-Agent", "UseBlessingSkinPlugin/1.0");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Charset", "UTF-8");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

OutputStream out = new DataOutputStream(conn.getOutputStream());

// 文件
File file = new File(picPath);

// 构建Body Header
String PostBody = "--" +
BOUNDARY +
"\r\n" +
"Content-Disposition: form-data; name=\"file\"; filename=\"" + picName + "\"" + "\r\n" +
"Content-Type: image/png" +
"\r\n" +
"\r\n";

// 将Body Header写入输出流
out.write(PostBody.getBytes());

// 读取文件数据
DataInputStream in = new DataInputStream(new FileInputStream(
file));

// 每次读1KB
byte[] bufferOut = new byte[1024];
int bytes;

// 写入输出流
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
File filePath = new File(picPath);
MediaType mediaType = MediaType.parse("image/png");

// 构建请求体
MultipartBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", picName, RequestBody.create(filePath, mediaType))
.build();

// 构建请求
Request request = new Request.Builder()
.url(urlHttp)
.post(requestBody)
.addHeader("User-Agent", "UseBlessingSkinPlugin/1.0")
.build();

// 执行请求并获取响应
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new IOException("HTTP error code: " + response.code() + " | " + response.message());
}

return response.body() != null ? response.body().string() : "{}";
}

// 添加换行
out.write("\r\n".getBytes());
in.close();

// 定义结尾数据分割线。
byte[] end_data = ("\r\n" + "--" + BOUNDARY + "--" + "\r\n").getBytes();

// 添加结尾标识
out.write(end_data);
out.flush();
out.close();

// 定义BufferedReader输入流来读取URL的响应
BufferedReader reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}

return response.toString();
}
}
}

0 comments on commit 368fdd1

Please sign in to comment.