Retrofit源码分析-前

来源:互联网 发布:威行通淘宝代运营如何 编辑:程序博客网 时间:2024/06/07 22:04

帮助博客:刘望舒http://liuwangshu.cn/application/network/9-retrofit2.html
文件上传:http://blog.csdn.net/jdsjlzx/article/details/51588617

出生:
Retrofit是Square公司开发的一款针对Android网络请求的框架,Retrofit2底层基于OkHttp实现的。

使用:
依赖
dependencies {

compile ‘com.squareup.retrofit2:retrofit:2.1.0’
compile ‘com.squareup.retrofit2:converter-gson:2.1.0’
compile ‘com.squareup.retrofit2:converter-scalars:2.1.0’//ConverterFactory的String依赖包
}
权限:

栗子接口:
/service/getIpInfo.php?ip=[ip地址字串]

使用Retrofit异步访问网络
用GsonFormat解析JSON,生成IpModel,IpData Bean类。

请求网络

public interface IpService{     @GET("getIpInfo.php")    Call<IpModel> getIpMsg(@Query("ip")String ip);}

Retrofit提供了请求方式用的是注解,有@POST,@GET,分别代表GET,POST请求,我们在这里访问的界面是”getIpInfo.php“。参数的注解有@PATH和@Query等,@Query就是我们的请求的键值对的设置,这里@Query(“ip”)代表健,“Stringip”代表值。

创建Retrofit

String url = "http://ip.taobao.com/service/";     Retrofit retrofit = new Retrofit.Builder()             .baseUrl(url)             //增加返回值为String的支持             .addConverterFactory(ScalarsConverterFactory.create())             .addConverterFactory(GsonConverterFactory.create())             .build();

这里baseUrl传入的参数是请求地址,addConverterFactory用于指定饭回的参数数据类型,这里我们支持String和Gson类型。

用Retrofit创建接口文件

IpService ipService = retrofit.create(IpService.class);Call<IpModel>call=ipService.getIpMsg(ip);

用retrofit创建我们之前定义的IpService接口对象,并调用该接口定义的getIpMsg方法得到Call对象。

用Call请求网络并处理回调

call.enqueue(new Callback<IpModel>() {           @Override           public void onResponse(Call<IpModel> call, Response<IpModel> response) {              String country= response.body().getData().getCountry();               Log.i("wangshu","country"+country);               Toast.makeText(getApplicationContext(),country,Toast.LENGTH_SHORT).show();           }           @Override           public void onFailure(Call<IpModel> call, Throwable t) {           }       });

这里是异步请求网络,回调的Callback是运行在主线程的。得到返回的Response后将返回数据的country字段用Toast显示出来。如果想同步请求网络请使用 call.execute(),如果想中断网络请求则可以使用 call.cancel()。

完整的代码如下

public class MainActivity extends AppCompatActivity {    private Button bt_request;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        bt_request = (Button) findViewById(R.id.bt_request);        bt_request.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                getIpInformation("59.108.54.37");            }        });    }    private void getIpInformation(String ip) {        String url = "http://ip.taobao.com/service/";        Retrofit retrofit = new Retrofit.Builder()                .baseUrl(url)                //增加返回值为String的支持                .addConverterFactory(ScalarsConverterFactory.create())                .addConverterFactory(GsonConverterFactory.create())                .build();        IpService ipService = retrofit.create(IpService.class);        Call<IpModel>call=ipService.getIpMsg(ip);        call.enqueue(new Callback<IpModel>() {            @Override            public void onResponse(Call<IpModel> call, Response<IpModel> response) {               String country= response.body().getData().getCountry();                Log.i("wangshu","country"+country);                Toast.makeText(getApplicationContext(),country,Toast.LENGTH_SHORT).show();            }            @Override            public void onFailure(Call<IpModel> call, Throwable t) {            }        });    }

到这里就是一个简单的使用流程,我来一个小段总结:
在我们添加依赖,权限,得到接口之后,写一个请求网络接口,这个接口中需要写一个注释声明这个方法是什么类型的请求,GET或POST,这个栗子中的方法就是Call方法泛型就是返回的类型,方法中参数也需要注解声明这个栗子中用的是@Query它就是声明的键值对,在这之后我们就可以创建Retrofit对象了将网址放入baseUri方法中,用addConverterFactory指定返回参数的数据类型,栗子中支持了GSON,String。之后我们就可以调用之前写的网络接口了我们用retrofit对象的create调用这个接口返回一个接口对象,我们用这个接口对象调取接口中的方法传入参数得到返回的Call对象,最后我们就可以调用Call对象的异步或同步方法,重写Callback在请求成功中得到数据。