package com.xcong.excoin.modules.newPrice;
|
|
|
import cn.hutool.json.JSONException;
|
import com.xcong.excoin.common.exception.FebsException;
|
import com.xcong.excoin.modules.newPrice.utils.JSONParser;
|
import com.xcong.excoin.modules.newPrice.utils.OkHttpUtils;
|
import okhttp3.Request;
|
import okhttp3.Response;
|
import okhttp3.ResponseBody;
|
|
import java.io.IOException;
|
|
public final class ResponseHandler {
|
|
private static final int HTTP_STATUS_CODE_400 = 400;
|
private static final int HTTP_STATUS_CODE_499 = 499;
|
private static final int HTTP_STATUS_CODE_500 = 500;
|
|
private ResponseHandler() {
|
}
|
|
public static String handleResponse(Request request, boolean showLimitUsage) {
|
try {
|
OkHttpUtils.builder();
|
try (Response response = OkHttpUtils.okHttpClient.newCall(request).execute()) {//OkHttpUtils.builder().okHttpClient
|
String responseAsString = getResponseBodyAsString(response.body());
|
|
if (response.code() >= HTTP_STATUS_CODE_400 && response.code() <= HTTP_STATUS_CODE_499) {
|
throw handleErrorResponse(responseAsString, response.code());
|
} else if (response.code() >= HTTP_STATUS_CODE_500) {
|
System.out.println("handleResponse:"+response.code());
|
throw new FebsException("responseAsString-"+responseAsString+";handleResponse-"+response.code());
|
}
|
return responseAsString;
|
// if (showLimitUsage) {
|
// return getlimitUsage(response, responseAsString);
|
// } else {
|
// return responseAsString;
|
// }
|
}
|
} catch (IOException | IllegalStateException e) {
|
e.printStackTrace();
|
throw new FebsException("[ResponseHandler] OKHTTP Error: " + e.getMessage());
|
}
|
}
|
|
|
private static FebsException handleErrorResponse(String responseBody, int responseCode) {
|
try {
|
String errorMsg = JSONParser.getJSONStringValue(responseBody, "msg");
|
int errorCode = JSONParser.getJSONIntValue(responseBody, "code");
|
return new FebsException("responseBody-"+responseBody+";errorMsg-"+errorMsg+";responseCode-"+responseCode+";errorCode-"+errorCode);
|
} catch (JSONException e) {
|
throw new FebsException("responseBody-"+responseBody+";responseCode-"+responseCode);
|
}
|
}
|
|
private static String getResponseBodyAsString(ResponseBody body) throws IOException {
|
if (null != body) {
|
return body.string();
|
} else {
|
return "";
|
}
|
}
|
}
|