Search in sources :

Example 6 with MediaType

use of com.squareup.okhttp.MediaType in project bdcodehelper by boredream.

the class ErrorInfoUtils method parseHttpErrorInfo.

/**
     * 解析服务器错误信息
     */
public static String parseHttpErrorInfo(Throwable throwable) {
    String errorInfo = throwable.getMessage();
    if (throwable instanceof HttpException) {
        // 如果是Retrofit的Http错误,则转换类型,获取信息
        HttpException exception = (HttpException) throwable;
        ResponseBody responseBody = exception.response().errorBody();
        MediaType type = responseBody.contentType();
        // 如果是application/json类型数据,则解析返回内容
        if (type.type().equals("application") && type.subtype().equals("json")) {
            try {
                // 这里的返回内容是Bmob/AVOS/Parse等RestFul API文档中的错误代码和错误信息对象
                ErrorResponse errorResponse = new Gson().fromJson(responseBody.string(), ErrorResponse.class);
                errorInfo = getLocalErrorInfo(errorResponse);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    } else {
        if (throwable instanceof UnknownHostException) {
            errorInfo = "无法连接到服务器";
        }
    }
    return errorInfo;
}
Also used : UnknownHostException(java.net.UnknownHostException) MediaType(com.squareup.okhttp.MediaType) Gson(com.google.gson.Gson) HttpException(retrofit.HttpException) UnknownHostException(java.net.UnknownHostException) HttpException(retrofit.HttpException) ResponseBody(com.squareup.okhttp.ResponseBody) ErrorResponse(com.boredream.bdcodehelper.entity.ErrorResponse)

Aggregations

MediaType (com.squareup.okhttp.MediaType)6 Request (com.squareup.okhttp.Request)4 Response (com.squareup.okhttp.Response)4 IOException (java.io.IOException)4 RequestBody (com.squareup.okhttp.RequestBody)3 ResponseBody (com.squareup.okhttp.ResponseBody)3 Intent (android.content.Intent)2 ErrorResponse (com.boredream.bdcodehelper.entity.ErrorResponse)2 Gson (com.google.gson.Gson)2 Connection (com.squareup.okhttp.Connection)2 OkHttpClient (com.squareup.okhttp.OkHttpClient)2 UnknownHostException (java.net.UnknownHostException)2 JSONException (org.json.JSONException)2 JSONObject (org.json.JSONObject)2 HttpException (retrofit.HttpException)2 AccountAuthenticatorResponse (android.accounts.AccountAuthenticatorResponse)1 AccountManager (android.accounts.AccountManager)1 SharedPreferences (android.content.SharedPreferences)1 Bundle (android.os.Bundle)1 DefaultResponseHandler (com.facebook.stetho.inspector.network.DefaultResponseHandler)1