原生态的Retrofit写网络请求

源代码路径

https://github.com/huxiubo1980/RetrofitDemoXiubo/

添加依赖

build.gradle添加依赖

compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4'

接口声明

public interface MovieService {
    /**请求方法*/
    @GET("top250")
    Call getTopMovie(@Query("start") int start, @Query("count") int count);
}

调用接口

在MainActivity调用(异步调用)

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(URL)
                .addConverterFactory(GsonConverterFactory.create()) /** json解析*/
                .build();
        /**这里是interface,so,需要创建一个代理*/
        MovieService movieService = retrofit.create(MovieService.class);
        /**拿到代理对象后就可以调用方法了*/
        Call call = movieService.getTopMovie(0, 2);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                Log.d(TAG, "respose = " + response.body().getTitle());
                tv.setText(response.body().getTitle());
            }

            @Override
            public void onFailure(Call call, Throwable t) {
                Log.d(TAG, "onFailure = " + t.getMessage());
            }
        });

同步调用
try {
    Response response = call.execute();
} catch (IOException e) {
    e.printStackTrace();
}

权限申请

  
    
    

你可能感兴趣的:(原生态的Retrofit写网络请求)