网络通信框架Retrofit2

一、 首先配置gradle文件

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

二、代码实现

1.定义一个接口文件

public interface RetrofitInterface {

    //注解,强调GET请求

    @GET(URLConstant.URL_PATH)

    Call  getObservable();

}

2.定义一个Constant类   定义基本的网页框架

public class URLConstant {

//基础地址

    public final static String URL_BASE = "http://m2.qiushibaike.com/";

//最新

    public final static String URL_PATH = "article/list/{type}?";

}

3.Retrofit2的使用(Activity中)

//首先创建一个Retrofit2对象

Retrofit retrofit = new Retrofit.Builder().baseUrl(Urls.BASEURLTWo).build();

//我们写的接口进行关联,获取接口对象

MyService myService = retrofit.create(MyService.class);

//用对象调用方法

myService.getObservable().enqueue(new Callback() { 

 @Override

//链接成功做的操作

 public void onResponse(Callcall, Response response) {

                try {

                    Log.e("Other项目的json", response.body().string());

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

//链接失败做的操作

@Override 

 public void onFailure(Call call, Throwable t) {

            }

        });

你可能感兴趣的:(网络通信框架Retrofit2)