Notice
Recent Posts
Recent Comments
Link
투케이2K
524. (Android/Java) [Okhttp 3.6.0] [RequestBody] post body json 요청 수행 및 응답 확인 실시 본문
Android
524. (Android/Java) [Okhttp 3.6.0] [RequestBody] post body json 요청 수행 및 응답 확인 실시
투케이2K 2023. 3. 27. 22:29[개발 환경 설정]
개발 툴 : AndroidStudio
[소스 코드]
[라이브러리 버전]
implementation 'com.squareup.okhttp3:okhttp:3.6.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.6.0'
[소스 코드]
// -----------------------------------------------------------------------------------------
// TODO [SEARCH FAST] : [POST BODY] : HTTP 수행
// -----------------------------------------------------------------------------------------
public static Observable<Boolean> requestAsyncPostBodyJsonHttp(String url, Map header, Map params){
// [로직 처리 실시]
return Observable.create(subscriber -> {
try {
//TODO [데이터 초기화]
postBodyResponseData = "";
//TODO [BODY에 파라미터 추가 실시]
RequestBody requestBody = null;
String bodyData = "";
if (params != null && params.size()>0){
// [json 데이터로 변경 실시]
bodyData = C_Util.mapToJsonObject(params).toString();
requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), bodyData);
}
//TODO [OK HTTP 객체 선언 실시]
//OkHttpClient client = new OkHttpClient();
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS) // [커넥션 제한 시간]
//.readTimeout(10, TimeUnit.SECONDS)
//.writeTimeout(10, TimeUnit.SECONDS)
.retryOnConnectionFailure(false)
.build();
Request.Builder request = new Request.Builder();
request.addHeader("Content-Type", "application/json"); //TODO [헤더]
request.addHeader("Cache-Control", "no-cache"); //TODO [헤더]
if (header != null && header.size()>0){
Set set = header.keySet();
Iterator iterator = set.iterator();
while(iterator.hasNext()){
String key = (String) iterator.next();
request.addHeader(key, String.valueOf(header.get(key))); //TODO [헤더 추가]
S_Log.d("---","---");
S_Log.d("//===========//","================================================");
S_Log.d("","\n"+"["+ACTIVITY_NAME+" > requestAsyncPostBodyJsonHttp() 메소드 : OK HTTP 비동기 POST [헤더] 추가]");
S_Log.d("","\n"+"["+"key : " + String.valueOf(key)+"]");
S_Log.d("","\n"+"["+"value : " + String.valueOf(String.valueOf(header.get(key)))+"]");
S_Log.d("//===========//","================================================");
S_Log.d("---","---");
}
}
if (requestBody != null){
request.post(requestBody);
}
else {
request.post(new FormBody.Builder().build());
}
request.url(url); //TODO [httpBuilder 추가]
S_Log.d("---","---");
S_Log.d("//===========//","================================================");
S_Log.d("","\n"+"["+ACTIVITY_NAME+" > requestAsyncPostBodyJsonHttp() 메소드 : OK HTTP 비동기 POST 요청 실시]");
S_Log.d("","\n"+"["+"요청 주소 : " + String.valueOf(url)+"]");
S_Log.d("","\n"+"["+"헤더 값 : " + String.valueOf(header)+"]");
S_Log.d("","\n"+"["+"전송 값 : " + String.valueOf(bodyData) +"]");
S_Log.d("//===========//","================================================");
S_Log.d("---","---");
//TODO [비동기 처리 (enqueue 사용)]
client.newCall(request.build()).enqueue(new Callback() {
//TODO [성공한 경우]
@Override
public void onResponse(Call call, Response response) throws IOException {
final String responseCode = String.valueOf(response.toString());
final String responseData = response.body().string();
S_Log.d("---","---");
S_Log.w("//===========//","================================================");
S_Log.d("","\n"+"["+ACTIVITY_NAME+" > requestAsyncPostBodyJsonHttp() 메소드 : OK HTTP 비동기 POST 요청 성공]");
S_Log.d("","\n"+"["+"응답 코드 : " + String.valueOf(responseCode)+"]");
S_Log.d("","\n"+"["+"응답 값 : " + String.valueOf(responseData)+"]");
S_Log.w("//===========//","================================================");
S_Log.d("---","---");
// ---------------------------------
// [응답 코드 값 체크]
try {
int statusCode = response.code();
if (statusCode >= 200 && statusCode < 300){
// [결과 전송 실시]
postBodyResponseData = String.valueOf(responseData);
subscriber.onNext(true);
subscriber.onComplete();
}
else {
// [결과 전송 실시]
postBodyResponseData = String.valueOf("\n"+"[TYPE] : " + "POST BODY"
+ "\n" +"[URL] : " + url
+ "\n"+"[ERROR] : [1] : " + "response status code : " + String.valueOf(statusCode));
subscriber.onNext(false);
subscriber.onComplete();
}
}
catch (Exception e){
e.printStackTrace();
// [결과 전송 실시]
postBodyResponseData = String.valueOf("\n"+"[TYPE] : " + "POST BODY"
+ "\n" +"[URL] : " + url
+ "\n"+"[ERROR] : [2] : " + String.valueOf(e.getMessage()));
subscriber.onNext(false);
subscriber.onComplete();
}
// ---------------------------------
}
//TODO [실패한 경우]
@Override
public void onFailure(Call call, IOException e) {
final String responseCode = String.valueOf(e.toString());
final String responseData = String.valueOf(e.getMessage());
S_Log.d("---","---");
S_Log.e("//===========//","================================================");
S_Log.d("","\n"+"["+ACTIVITY_NAME+" > requestAsyncPostBodyJsonHttp() 메소드 : OK HTTP 비동기 POST 요청 실패]");
S_Log.d("","\n"+"["+"에러 코드 : " + String.valueOf(responseCode)+"]");
S_Log.d("","\n"+"["+"에러 값 : " + String.valueOf(responseData)+"]");
S_Log.e("//===========//","================================================");
S_Log.d("---","---");
// ---------------------------------
// [결과 전송 실시]
postBodyResponseData = String.valueOf("\n"+"[TYPE] : " + "POST BODY"
+ "\n" +"[URL] : " + url
+ "\n"+"[ERROR] : [3] : " + String.valueOf(e.getMessage()));
subscriber.onNext(false);
subscriber.onComplete();
// ---------------------------------
}
});
} catch (final Exception e){
S_Log.d("---","---");
S_Log.e("//===========//","================================================");
S_Log.d("","\n"+"["+ACTIVITY_NAME+" > requestAsyncPostBodyJsonHttp() 메소드 : OK HTTP 비동기 POST 요청 실패 - CATCH]");
S_Log.d("","\n"+"["+"에러 값 : " + String.valueOf(e.getMessage())+"]");
S_Log.e("//===========//","================================================");
S_Log.d("---","---");
// ---------------------------------
// [결과 전송 실시]
postBodyResponseData = String.valueOf("\n"+"[TYPE] : " + "POST BODY"
+ "\n" +"[URL] : " + url
+ "\n"+"[ERROR] : [4] : " + String.valueOf(e.getMessage()));
subscriber.onNext(false);
subscriber.onComplete();
// ---------------------------------
e.printStackTrace();
}
});
}
반응형
'Android' 카테고리의 다른 글
Comments