Notice
Recent Posts
Recent Comments
Link
투케이2K
113. (spring/스프링) okhttp 사용해 post body json 요청 실시 본문
[개발 환경 설정]
개발 툴 : inteli j
개발 언어 : spring
[소스 코드]
package com.kwon.mssqltestproject;
import okhttp3.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
public class C_Okhttp {
/**
* // -----------------------------------------
* TODO [클래스 설명]
* // -----------------------------------------
* 1. okhttp 네트워크 요청 클래스
* // -----------------------------------------
* 2. 필요 build.gradle 설정 :
*
* implementation("com.squareup.okhttp3:okhttp:4.9.1")
* // -----------------------------------------
* */
/**
* // -----------------------------------------
* // TODO [빠른 로직 찾기 : 주석 로직 찾기]
* // -----------------------------------------
* // [SEARCH FAST] : [POST BODY JSON 요청 실시]
* // -----------------------------------------
* */
// TODO [전역 변수 선언]
private static final String CLASS_NAME = "C_Okhttp";
public static final String RES_SUCCESS = "RES_SUCCESS";
public static final String RES_STATUS = "RES_STATUS";
public static final String RES_HEADER = "RES_HEADER";
public static final String RES_DATA = "RES_DATA";
// TODO [SEARCH FAST] : [POST BODY JSON 요청 실시]
public static Map<String, Object> postBodyJson(String url, Map<String, Object> data){
System.out.println("\n");
System.out.println("================================================");
System.out.println("[CLASS] : "+String.valueOf(CLASS_NAME));
System.out.println("[METHOD] : "+String.valueOf("postBodyJson"));
System.out.println("[URL] : "+String.valueOf(url));
System.out.println("[DATA] : "+String.valueOf(data));
System.out.println("================================================");
System.out.println("\n");
/**
* // -----------------------------------------
* // TODO [호출 방법]
* // -----------------------------------------
* String url = "http://jsonplaceholder.typicode.com/posts";
*
* Map params = new HashMap();
* params.put("userId",1);
* params.put("id",1);
*
* Map response = C_Okhttp.postBodyJson(url, params);
* // -----------------------------------------
* */
// [초기 리턴 데이터 선언 실시]
Map<String, Object> returnData = new HashMap<>();
String urlData = String.valueOf(url.replaceAll(" ", ""));
// [로직 처리 실시]
try {
// [사전 주소 형식 체크 실시]
if (urlData != null && urlData.isEmpty() == false && urlData.length() > 0
&& urlData.trim().equals("") == false && urlData.trim().equals("null") == false
&& urlData.startsWith("http") == true){ // [널 아님]
}
else {
System.out.println("\n");
System.out.println("================================================");
System.out.println("[CLASS] : "+String.valueOf(CLASS_NAME));
System.out.println("[METHOD] : "+String.valueOf("postBodyJson"));
System.out.println("[ERROR] : "+String.valueOf("url is null"));
System.out.println("[RETURN] : "+String.valueOf(returnData));
System.out.println("================================================");
System.out.println("\n");
// [리턴 반환]
return returnData;
}
// [데이터 널 여부 체크 실시]
FormBody.Builder formBuilder = new FormBody.Builder();
if (data != null && data.isEmpty() == false && data.size()>0){ // [널 아님]
// [map 데이터 key, value 확인]
Set set = data.keySet();
Iterator iterator = set.iterator();
while(iterator.hasNext()){
String key = (String) iterator.next();
String value = String.valueOf(data.get(key));
// [바디에 추가 실시]
formBuilder.add(key, String.valueOf(value));
}
}
// [ok http 요청 실시]
System.out.println("\n");
System.out.println("================================================");
System.out.println("[CLASS] : "+String.valueOf(CLASS_NAME));
System.out.println("[METHOD] : "+String.valueOf("postBodyJson"));
System.out.println("[REQUEST] : [URL] : "+String.valueOf(urlData));
System.out.println("[REQUEST] : [BODY] : "+String.valueOf(data.toString()));
System.out.println("================================================");
System.out.println("\n");
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(20, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.retryOnConnectionFailure(false)
.build();
Request request = new Request.Builder()
.url(urlData)
.addHeader("Content-Type", "application/json;")
.addHeader("Cache-Control", "no-cache")
.post(formBuilder.build())
.build();
// [동기 요청 실시]
Call call = client.newCall(request);
Response response = call.execute();
if (response.code() >= 200 && response.code() < 300){
returnData.put(RES_SUCCESS, true);
}
else {
returnData.put(RES_SUCCESS, false);
}
returnData.put(RES_STATUS, response.code());
//returnData.put(RES_HEADER, response.headers());
returnData.put(RES_DATA, response.body().string());
}
catch (Exception e){
e.printStackTrace();
}
// [로그 결과 출력]
System.out.println("\n");
System.out.println("================================================");
System.out.println("[CLASS] : "+String.valueOf(CLASS_NAME));
System.out.println("[METHOD] : "+String.valueOf("postBodyJson"));
System.out.println("[RESPONSE] : "+String.valueOf(returnData));
System.out.println("================================================");
System.out.println("\n");
// [리턴 결과 반환 실시]
return returnData;
}
} // [클래스 종료]
[결과 출력]
반응형
'Spring' 카테고리의 다른 글
Comments