Rxjava2+Retrofit2结合mvp的简单教程Retrofit篇(一):Retrofit2的基本使用


本篇讲解内容:Retrofit2的基本使用

官方地址:http://square.github.io/retrofit/
github地址:https://github.com/square/retrofit

1.引用到项目 compile 'com.squareup.retrofit2:retrofit:2.3.0'
2.对比上篇中post请求来写retrofit请求(post请求的地址和参数和上篇一样,本篇开始只讲解post请求)

  • 首先看官方的介绍:Retrofit turns your HTTP API into a Java interface.意思是Retrofit 将http请求转化为java 接口,对应的代码操作就是,创建http接口类,我命名为RetrofitService,代码如下:
public interface RetrofitService {
    @POST("app/gift/gift_list/")
    Call getGameList(@Body RequestBody body);
}
  • 然后看看RetrofitActivity中调用的代码,与okhttp不一样的地方,首先就是将Url进行拆分,第二就是将请求统一写到一个接口类管理,最后调用enqueue,基本上也很简单。
public class RetrofitActivity extends AppCompatActivity {
    public static final String BASE_URL = "http://zhushou.72g.com/";//BASE_URL请以/结尾
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    private String TAG = "RetrofitActivity";
    private RetrofitService service;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //创建retrofit,将上篇中的POST_URL拆开,一部分在BASE_URL,一部分在RetrofitService的post参数中
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .build();
        //使用Retrofit 创建RetrofitService的实现
        service = retrofit.create(RetrofitService.class);
        //POST请求和上篇一样,创建请求体
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("page", "1");
            jsonObject.put("code", "news");
            jsonObject.put("pageSize", "20");
            jsonObject.put("parentid", "0");
            jsonObject.put("type", "1");
            post(jsonObject.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    void post(String jsonObject) throws IOException {
        RequestBody body = RequestBody.create(JSON, jsonObject.toString());
        Call responseBodyCall = service.getGameList(body);
        responseBodyCall.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                try {
                    Log.d(TAG, "get response=" + response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onFailure(Call call, Throwable t) {
            }
        });
    }
}

好了到此为止你已经学会了retrofit了,是不是很简单,下一篇我们将对retrofit进行简单的封装,为什么现在封装,是因为有些小伙伴接下来可能不需要使用rxjava,毕竟学习rxjava不像retrofit这么简单。

你可能感兴趣的:(Rxjava2+Retrofit2结合mvp的简单教程Retrofit篇(一):Retrofit2的基本使用)