Notice
Recent Posts
Recent Comments
Link
투케이2K
531. (Android/Java) [okhttp 4.9.0] [유틸 파일] a: put 방식 비동기 http 요청 수행 본문
[개발 환경 설정]
개발 툴 : AndroidStudio
[소스 코드]
// -----------------------------------------------------------------------------------------
// TODO [SEARCH FAST] : [PUT] : [BODY JSON] : requestPutBodyJsonHttp
// -----------------------------------------------------------------------------------------
// TODO [호출 방법 소스 코드]
// -----------------------------------------------------------------------------------------
/*
try {
// [URL 주소 선언]
String url = "https://jsonplaceholder.typicode.com/posts/1";
// [파라미터 생성]
Map <String, Object> params = new HashMap<>();
params.put("userId", 1);
params.put("id", 1);
params.put("bar", "foo");
params.put("title", "foo");
// [http 요청 수행]
N_AsyncHttp.requestPutBodyJsonHttp(url, null, params) // [http 요청]
.subscribeOn(AndroidSchedulers.mainThread()) // [Observable (생성자) 로직을 IO 스레드에서 실행 : 백그라운드]
.observeOn(Schedulers.io()) // [Observer (관찰자) 로직을 메인 스레드에서 실행]
.subscribe(new Observer<String>() { // [Observable.create 타입 지정]
@Override
public void onSubscribe(@NonNull Disposable d) {
}
@Override
public void onNext(@NonNull String value) {
S_Log.ltw("================================================");
S_Log.cnt("["+ACTIVITY_NAME+" >> requestPutBodyJsonHttp :: onNext]");
S_Log.cnt("-----------------------------------------");
S_Log.cnt("[VALUE :: "+String.valueOf(value)+"]");
S_Log.lbw("================================================");
}
@Override
public void onError(@NonNull Throwable e) {
S_Log.lte("================================================");
S_Log.cnt("["+ACTIVITY_NAME+" >> requestPutBodyJsonHttp :: onError]");
S_Log.cnt("-----------------------------------------");
S_Log.cnt("[ERROR :: "+String.valueOf(e.getMessage())+"]");
S_Log.lbe("================================================");
}
@Override
public void onComplete() {
}
});
}
catch (Exception e){
e.printStackTrace();
}
*/
// -----------------------------------------------------------------------------------------
public static Observable<String> requestPutBodyJsonHttp(String url, Map header, Map params){
// [로직 처리 실시]
return Observable.create(subscriber -> {
try {
// ------------------------------------------------------
// TODO [URL 변수 선언 실시]
String urlData = String.valueOf(url);
// ------------------------------------------------------
// ------------------------------------------------------
// TODO [BODY에 파라미터 추가 실시]
RequestBody requestBody = null;
String bodyData = "";
if (C_Util.mapNotNull(params) == true) { // [파라미터가 있는 경우]
// [json 데이터로 변경 실시]
bodyData = C_Util.mapToJsonObject(params).toString();
requestBody = RequestBody.create(bodyData, MediaType.parse("application/json; charset=utf-8"));
}
// ------------------------------------------------------
// ------------------------------------------------------
// 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 (C_Util.mapNotNull(header) == true){
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.ltd("================================================");
S_Log.cnt("["+ACTIVITY_NAME+" >> requestPutBodyJsonHttp :: OK HTTP 비동기 PUT BODY JSON [헤더] 추가]");
S_Log.cnt("-----------------------------------------");
S_Log.cnt("[KEY :: "+String.valueOf(key)+"]");
S_Log.cnt("-----------------------------------------");
S_Log.cnt("[VALUE :: "+String.valueOf(header.get(key))+"]");
S_Log.lbd("================================================");
}
}
HttpUrl.Builder httpBuilder = HttpUrl.get(URI.create(urlData)).newBuilder();
if (requestBody != null){
request.put(requestBody);
}
else {
request.put(new FormBody.Builder().build());
}
request.url(httpBuilder.build()); //TODO [httpBuilder 추가]
// ------------------------------------------------------
// ------------------------------------------------------
// TODO [요청 로그 출력 실시]
S_Log.ltw("================================================");
S_Log.cnt("["+ACTIVITY_NAME+" >> requestPutBodyJsonHttp :: OK HTTP 비동기 PUT BODY JSON [요청] 실시]");
S_Log.cnt("-----------------------------------------");
S_Log.cnt("[TYPE :: PUT BODY JSON >> REQUEST]");
S_Log.cnt("-----------------------------------------");
S_Log.cnt("[URL :: "+String.valueOf(urlData)+"]");
S_Log.cnt("-----------------------------------------");
S_Log.cnt("[HEADER :: "+String.valueOf(header)+"]");
S_Log.cnt("-----------------------------------------");
S_Log.cnt("[BODY :: "+String.valueOf(bodyData)+"]");
S_Log.lbw("================================================");
// ------------------------------------------------------
// ------------------------------------------------------
//TODO [비동기 처리 (enqueue 사용)]
String finalUrlData = urlData;
client.newCall(request.build()).enqueue(new Callback() {
// TODO [성공한 경우]
@Override
public void onResponse(Call call, Response response) throws IOException {
final String responseUrl = String.valueOf(finalUrlData);
final String responseHeader = String.valueOf(response.headers().toString());
final String responseCode = String.valueOf(response.code());
final String responseData = String.valueOf(response.body().string());
S_Log.ltw("================================================");
S_Log.cnt("["+ACTIVITY_NAME+" >> requestPutBodyJsonHttp :: OK HTTP 비동기 PUT BODY JSON [응답] 확인]");
S_Log.cnt("-----------------------------------------");
S_Log.cnt("[TYPE :: PUT BODY JSON >> RESPONSE]");
S_Log.cnt("-----------------------------------------");
S_Log.cnt("[CODE :: "+String.valueOf(responseCode)+"]");
S_Log.cnt("-----------------------------------------");
S_Log.cnt("[URL :: "+String.valueOf(responseUrl)+"]");
S_Log.cnt("-----------------------------------------");
S_Log.cnt("[HEADER :: "+String.valueOf(responseHeader)+"]");
S_Log.cnt("-----------------------------------------");
S_Log.cnt("[DATA :: "+String.valueOf(responseData)+"]");
S_Log.lbw("================================================");
// ------------------------------------------------------
// TODO [응답 코드 값 체크 및 리턴 데이터 반환]
// ------------------------------------------------------
try {
int statusCode = response.code();
if (statusCode >= 200 && statusCode < 300){ // TODO [정상 응답]
// TODO [결과 전송 실시]
subscriber.onNext(responseData);
subscriber.onComplete();
}
else { // TODO [에러 응답]
subscriber.onError(new Throwable("[ERROR] : : [requestPutBodyJsonHttp] : " + C_Msg.getErrorHttpMsg(responseCode)));
}
}
catch (Exception e){
e.printStackTrace();
subscriber.onError(new Throwable("[EXCEPTION] : [1] : [requestPutBodyJsonHttp] : " + e.getMessage()));
}
// ------------------------------------------------------
}
//TODO [실패한 경우]
@Override
public void onFailure(Call call, IOException e) {
final String responseUrl = String.valueOf(finalUrlData);
final String responseError = String.valueOf(e.getMessage());
S_Log.lte("================================================");
S_Log.cnt("["+ACTIVITY_NAME+" >> requestPutBodyJsonHttp :: OK HTTP 비동기 PUT BODY JSON [에러] 확인]");
S_Log.cnt("-----------------------------------------");
S_Log.cnt("[TYPE :: PUT BODY JSON >> FAIL]");
S_Log.cnt("-----------------------------------------");
S_Log.cnt("[URL :: "+String.valueOf(responseUrl)+"]");
S_Log.cnt("-----------------------------------------");
S_Log.cnt("[ERROR :: "+String.valueOf(responseError)+"]");
S_Log.lbe("================================================");
// ------------------------------------------------------
// TODO [리턴 데이터 반환]
// ------------------------------------------------------
try {
subscriber.onError(new Throwable("[FAIL] : [requestPutBodyJsonHttp] : " + responseError));
}
catch (Exception ex){
ex.printStackTrace();
}
}
});
} catch (final Exception e){
e.printStackTrace();
S_Log.lte("================================================");
S_Log.cnt("["+ACTIVITY_NAME+" >> requestPutBodyJsonHttp :: OK HTTP 비동기 PUT BODY JSON [Exception] 확인]");
S_Log.cnt("-----------------------------------------");
S_Log.cnt("[TYPE :: PUT BODY JSON >> EXCEPTION]");
S_Log.cnt("-----------------------------------------");
S_Log.cnt("[EXCEPTION :: "+String.valueOf(e.getMessage())+"]");
S_Log.lbe("================================================");
// ------------------------------------------------------
// TODO [리턴 데이터 반환]
// ------------------------------------------------------
try {
subscriber.onError(new Throwable("[EXCEPTION] : [2] : [requestPutBodyJsonHttp] : " + String.valueOf(e.getMessage())));
}
catch (Exception ex){
ex.printStackTrace();
}
}
});
}
[결과 출력]
W///===========//: ================================================
I/: [A_Intro >> requestPutBodyJsonHttp :: onNext]
I/: -----------------------------------------
I/: [VALUE :: {
"bar": "foo",
"id": 1,
"title": "foo",
"userId": 1
}]
W///===========//: ================================================
반응형
'Android' 카테고리의 다른 글
Comments