Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Android Http Exception #207

Open
soapgu opened this issue Jul 10, 2023 · 0 comments
Open

Android Http Exception #207

soapgu opened this issue Jul 10, 2023 · 0 comments
Labels
安卓 安卓

Comments

@soapgu
Copy link
Owner

soapgu commented Jul 10, 2023

  • 前言

安卓中的Http组件对异常处理的总结

  • OKHttp

OKHttp对http的包装处于“初级阶段”,并不“干涉”http协议层的错误处理,主要处理IO方面的异常

private void getDataAsync() {
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder()
            .url("http://www.baidu.com")
            .build();
    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
        }
        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if(response.isSuccessful()){//回调的方法执行在子线程。
                Log.d("kwwl","获取数据成功了");
                Log.d("kwwl","response.code()=="+response.code());
                Log.d("kwwl","response.body().string()=="+response.body().string());
            }
        }
    });
}

举例说明:
这里我们使用异步的方式调用。
其中onFailure的处理,只有IOException的处理
onResponse的处理,这里的response对象,包括了stateCode 非2XX的处理

  • Retrofit

Retrofit的组件更加深入业务层,直接返回的是“业务对象”

举例

@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId);

直接返回的是User对象。
这样所有的StateCode就必须是2XX,否则会引发retrofit2.HttpException

  • HttpException
    如果要获取异常情况下的body怎么获取?主要有两种方式
  1. Handle HttpException
图片 可以通过response方法获取retrofit2.Response对象 图片 通过调用[errorBody](https://square.github.io/retrofit/2.x/retrofit/retrofit2/Response.html#errorBody--),获取异常stateCode的body。
  1. Call对象包装retrofit2.Response对象

比如

//转换前
@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId);

//转换后
@GET("group/{id}/users")
Call<retrofit2.Response<List<User>>> groupList(@Path("id") int groupId);

自己判断stateCode以及处理body

if( response.isSuccessful ){
    //正常处理
    List<User> users = response.body();
    //其他业务逻辑
} else {
   //解析body的异常
   showErrorMessage( response.errorBody() );
}
@soapgu soapgu added the 安卓 安卓 label Jul 10, 2023
@soapgu soapgu changed the title Android Http Excetion Android Http Exception Jul 10, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
安卓 安卓
Projects
None yet
Development

No branches or pull requests

1 participant