1、什么是Retrofit框架?
它是Square公司开发的现在非常流行的网络框架,所以我们在导入它的包的时候都可以看到这个公司的名字,目前的版本是2。
特点:
性能好,处理快,使用简单,Retrofit 是安卓上最流行的HTTP Client库之一
使用REST API设计风格 支持 NIO(new i/o) 默认使用OKHttp处理网络请求,我觉得可以看成是OKHttp的增强。 默认使用Gson解析测试Url:
其中是BASE_URL,也就是基础地址,basil2style是GET的参数,如果访问成功会返回给我们一个json字符串:
{ "login": "basil2style", "id": 1285344, "avatar_url": "https://avatars.githubusercontent.com/u/1285344?v=3", "gravatar_id": "", "url": "https://api.github.com/users/basil2style", "html_url": "https://github.com/basil2style", "followers_url": "https://api.github.com/users/basil2style/followers", "following_url": "https://api.github.com/users/basil2style/following{/other_user}", "gists_url": "https://api.github.com/users/basil2style/gists{/gist_id}", "starred_url": "https://api.github.com/users/basil2style/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/basil2style/subscriptions", "organizations_url": "https://api.github.com/users/basil2style/orgs", "repos_url": "https://api.github.com/users/basil2style/repos", "events_url": "https://api.github.com/users/basil2style/events{/privacy}", "received_events_url": "https://api.github.com/users/basil2style/received_events", "type": "User", "site_admin": false, "name": "Basil", "company": "MakeInfo", "blog": "http://www.themakeinfo.com", "location": "Peterborough,ON,Canada", "email": "basiltalias92@gmail.com", "hireable": true, "bio": null, "public_repos": 45, "public_gists": 4, "followers": 52, "following": 145, "created_at": "2011-12-26T00:17:22Z", "updated_at": "2016-06-23T20:22:05Z"}
- 1
- 2
- 3
好,按步骤开始写代码
1、定义一个接口(封装URL地址和数据请求)
RequestServices.javapackage com.example.eventbus.retrofittest;import okhttp3.ResponseBody;import retrofit2.Call;import retrofit2.http.GET;/** * Created by LHD on 2016/6/25. */public interface RequestServices { //请求方式为GET,参数为basil2style,因为没有变量所以下面getString方法也不需要参数 @GET("basil2style") //定义返回的方法,返回的响应体使用了ResponseBody CallgetString();}
- 1
- 2
- 3
我们通常把基础地址都放在一个类里,方便调用
Constant.javapackage com.example.eventbus.retrofittest;/** * Created by LHD on 2016/6/25. */public class Constant { //baseurl public final static String URL_BASE = "https://api.github.com/users/";}
- 1
- 2
- 3
2、实例化Retrofit
//获取Retrofit对象,设置地址 Retrofit retrofit = new Retrofit.Builder() .baseUrl(Constant.URL_BASE) .build();
- 1
- 2
- 3
3、通过Retrofit实例创建接口服务对象
RequestServices requestServices = retrofit.create(RequestServices.class);
- 1
4、接口服务对象调用接口中方法,获得Call对象
Callcall = requestServices.getString();
- 1
5、Call对象执行请求(异步、同步请求)
call.enqueue(new Callback() { @Override public void onResponse(Call call, Response response) { if (response.isSuccess()){ try { Log.i("LHD",response.body().toString()); //返回的结果保存在response.body()中 String result = response.body().string(); //onResponse方法是运行在主线程也就是UI线程的,所以我们可以在这里 //直接更新UI textView.setText(result); } catch (IOException e) { e.printStackTrace(); } } } @Override public void onFailure(Call call, Throwable t) { Log.i("LHD","访问失败"); } });