Retrofit 是 Square 公司出品的 HTTP 请求库, 同时是 Square 是最早开源项目之一, Retrofit 是目前 Android 最流行的 Http Client 库之一, 目前版本是 Retrofit2.0 Beta4, 越来越多 Android 开发者开始使用这个请求库了

1、配置环境

在build.gradle文件中导入依赖包,一个为retrofit包,还有一个为Json转换包

compile 'com.squareup.retrofit2:retrofit:2.1.0'compile 'com.squareup.retrofit2:converter-gson:2.1.0'
在Android Studio中加入Retrofit包后,系统会自动加入OkHttp包进入项目,Retrofit推出的2.0版本之后,直接强制用户使用OkHttp做网络请求,所以可以说Retorfit和OkHttp已经是一对兄弟关系。

在AndroidManifest.xml文件中加入网络请求权限

2、定义网络请求接口

例子详细地址:

http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=218.4.255.255

public interface ApiService {    //获取详情数据    @GET("iplookup/iplookup.php?")    Call getLocationData(@Query("format") String format, @Query("ip") String ip);    @POST("iplookup/iplookup.php?")    Call postLocationData(@Query("format") String format, @Query("ip") String ip);}

@GET为Http中的get请求,后面请求的参数表示请求的路径但是不包含域名。

@Post为Http中的post请求,参数与get请求相同,在Post请求上添加@FormUrlEncoded注解表示以表单的方式来提交参数

@Query后面表示参数,前面是键后面参数为值。

3、定义实体类
public class LocationBean {    /**     * ret : 1     * start : -1     * end : -1     * country : 中国     * province : 江苏     * city : 苏州     * district :     * isp :     * type :     * desc :     */    private int ret;    private int start;    private int end;    private String country;    private String province;    private String city;    private String district;    private String isp;    private String type;    private String desc;    public int getRet() {        return ret;    }    public void setRet(int ret) {        this.ret = ret;    }   ......}
可以通过 GsonFormat 转换器将json数据生成实体类, GsonFormat 是Android Studio中的插件,效果如下:

配置方法:

Android studio File->Settings..->Plugins>Browse repositores..搜索GsonFormat
安装插件,重启android studio

3、 创建一个Retrofit对象

Retrofit retrofit = new Retrofit.Builder()        //域名        .baseUrl("http://int.dpool.sina.com.cn/")        //增加返回值为Gson的支持(以实体类返回)        .addConverterFactory(GsonConverterFactory.create())        .build();
baseUrl()后面的参数为请求域名,建议写一个全局变量,方便后期更改
addConverterFactory(GsonConverterFactory.create())的意思是构建一个返回值支持,后面可通过Call接收到实体类返回值。

4、网络请求

ApiService apiService = retrofit.create(ApiService.class);//这里采用的是Java的动态代理模式Call call = apiService.postLocationData("json", "218.4.255.255");//传入我们请求的键值对的值call.enqueue(new Callback() {    @Override    public void onResponse(Call call, Response response) {        //服务器响应        LocationBean bean = response.body();        Log.e("TAG", "body.getMessage()===" + bean.getCity());        content.setText(bean.getCity());    }    @Override    public void onFailure(Call call, Throwable t) {        //请求失败    }});
使用retrofit 方法请求网络,并得到返回值的实体类, json 解析过程也帮我们完成了 ,并且 onResponse和onFailure方法是在 UI线程,可以通过回调直接更新UI界面。

5、示例

public class MainActivity extends Activity {    private Button btn;    private TextView content;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        btn = (Button) findViewById(R.id.btn);        content = (TextView) findViewById(R.id.content);        btn.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                RetrofitTest();            }        });    }    private void RetrofitTest() {        Retrofit retrofit = new Retrofit.Builder()                //域名                .baseUrl("http://int.dpool.sina.com.cn/")                //增加返回值为Gson的支持(以实体类返回)                .addConverterFactory(GsonConverterFactory.create())                .build();        ApiService apiService = retrofit.create(ApiService.class);//这里采用的是Java的动态代理模式        Call call = apiService.postLocationData("json", "218.4.255.255");//传入我们请求的键值对的值        call.enqueue(new Callback() {            @Override            public void onResponse(Call call, Response response) {                //服务器响应                LocationBean bean = response.body();                Log.e("TAG", "body.getMessage()===" + bean.getCity());                content.setText(bean.getCity());            }            @Override            public void onFailure(Call call, Throwable t) {                //请求失败            }        });    }}
XML:

<?xml version="1.0" encoding="utf-8"?>    




更多相关文章

  1. mybatisplus的坑 insert标签insert into select无参数问题的解决
  2. Python技巧匿名函数、回调函数和高阶函数
  3. python list.sort()根据多个关键字排序的方法实现
  4. Android(安卓)Service+Socket 联网交互
  5. Android中图像和图像处理
  6. Android利用Fiddler进行网络数据抓包
  7. 安卓入门及界面带参数跳转
  8. android的几种网络请求方式详解
  9. Android(安卓)启动 白屏问题 解决

随机推荐

  1. android 中文粗体
  2. Android文件的读写
  3. android studio 在线更新android sdk,遇到
  4. Android PULL解析XML
  5. android gps开发
  6. 点击事件
  7. Android(安卓)Instrumentation基础使用
  8. SHA-1 fingerprint of keystore certific
  9. android GestureDetector应用
  10. Android原生(Native)C开发