최초 세팅
This commit is contained in:
52
src/main/java/com/madeuhome/util/OkHttpService.java
Normal file
52
src/main/java/com/madeuhome/util/OkHttpService.java
Normal file
@@ -0,0 +1,52 @@
|
||||
package com.madeuhome.util;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import okhttp3.MultipartBody;
|
||||
import okhttp3.OkHttpClient;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.Response;
|
||||
|
||||
@Component
|
||||
public class OkHttpService {
|
||||
private static final OkHttpClient client = new OkHttpClient.Builder()
|
||||
.connectTimeout(30, TimeUnit.SECONDS)
|
||||
.writeTimeout(30, TimeUnit.SECONDS)
|
||||
.readTimeout(30, TimeUnit.SECONDS)
|
||||
.build();
|
||||
|
||||
/**
|
||||
* Form-data POST 요청
|
||||
* @param url 요청 URL
|
||||
* @param formData 폼 데이터
|
||||
* @return 응답 문자열
|
||||
* @throws IOException 요청 실패시
|
||||
*/
|
||||
public static String postFormData(String url, Map<String, String> formData) throws IOException {
|
||||
MultipartBody.Builder builder = new MultipartBody.Builder()
|
||||
.setType(MultipartBody.FORM);
|
||||
|
||||
// 폼 데이터 추가
|
||||
for (Map.Entry<String, String> entry : formData.entrySet()) {
|
||||
if (entry.getValue() != null) {
|
||||
builder.addFormDataPart(entry.getKey(), entry.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
Request request = new Request.Builder()
|
||||
.url(url)
|
||||
.post(builder.build())
|
||||
.build();
|
||||
|
||||
try (Response response = client.newCall(request).execute()) {
|
||||
if (!response.isSuccessful()) {
|
||||
throw new IOException("HTTP Error: " + response.code() + " " + response.message());
|
||||
}
|
||||
return response.body().string();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user