Retrofit2学习之一:HelloWorld

Retrofit简介

Retrofit是Square公司开发的一款针对Android网络请求的框架,Retrofit与OKhttp共同出自于Square公司,Retrofit2底层基于OkHttp实现的,OkHttp现在已经得到Google官方认可,大量的app都采用OkHttp做网络请求。

Retrofit把网络请求交给OKhttp,只需要通过简单的配置就能使用retrofit实现网络请求。

安装使用

Github:https://github.com/square/retrofit

在app层级的build.gradle配置

compile 'com.squareup.retrofit2:retrofit:2.1.0'

Hello World

创建业务请求接口

public interface Api {

    @GET("user/1")
    Call<ResponseBody> getUser();

}

创建一个Retrofit的实例,并利用Retrofit实例创建接口对象和调用接口方法

public void hello(View view) {
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(SERVER_ADDRESS)
            .build();

    Api api = retrofit.create(Api.class);

    Call<ResponseBody> call = api.getUser();
    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            //在UI主线程运行
            if (response.isSuccessful()) {
                Log.i(TAG, "返回成功");
                ResponseBody body = response.body();
                if (body != null) {
                    String result = null;
                    try {
                        result = body.string();
                        JSONObject json = new JSONObject(result);
                        String id = json.optString("id");
                        String username = json.optString("username");
                        String head_url = json.optString("head_url");
                        mTvNickName.setText(username);
                        Picasso.with(MainActivity.this).load(head_url).resize(100, 100).centerCrop().into(mIvAvatar);
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    } finally {
                        body.close();
                    }
                }
            }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            Log.i(TAG, "请求失败: " + t.getLocalizedMessage());
        }
    });
}
上一篇 OKHttp3学习之九:文件上传(拦截器获取上传进度)
下一篇 Retrofit2学习之二:Retrofit 转换器