Android知识Android开发经验谈Android技术知识

Rxjava2+Retrofit2结合mvp的简单教程Retro

2017-07-31  本文已影响379人  MrAllRight_Liu

本篇讲解内容: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请求)

public interface RetrofitService {
    @POST("app/gift/gift_list/")
    Call<ResponseBody> getGameList(@Body RequestBody body);
}
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<ResponseBody> responseBodyCall = service.getGameList(body);
        responseBodyCall.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    Log.d(TAG, "get response=" + response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
            }
        });
    }
}

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

上一篇 下一篇

猜你喜欢

热点阅读