首先介绍一下这东西,其实是okHttp的封装
Retrofit是由Square公司出品的针对于Android和Java的类型安全的Http客户端,
如果看源码会发现其实质上就是对okHttp的封装,使用面向接口的方式进行网络请求,利用动态生成的代理类封装了网络接口请求的底层,
其将请求返回javaBean,对网络认证 REST API进行了很好对支持此,使用Retrofit将会极大的提高我们应用的网络体验。
REST(REpresentational State Transfer)是一组架构约束条件和原则。
RESTful架构都满足以下规则:
(1)每一个URI代表一种资源;
(2)客户端和服务器之间,传递这种资源的某种表现层;
(3)客户端通过四个HTTP动词,对服务器端资源进行操作,实现”表现层状态转化”
摸索轨迹开始:
1.首先需要建立类似如下的interface,注解@GET是必须的,但可以是别的,比如POST等,这个暂时先不说,后面的是相对地址和查询条件(如果不懂http和url可以先百度),这个是用来获取返回数据以及返回何种数据。这里涉及到converter,代码中就是ResponseBody,这个默认的一种converter,你可以自己构造一个converter,这个是决定你获取到的数据是何种格式,retrofit会按照你定的这个converter来给你造数据
public interface GetRequest_Interface { @GET("openapi.do?keyfrom=Yanzhikai&key=2032414398&type=data&doctype=json&version=1.1&q=car") Call<ResponseBody> getCall(); }
2.创建retrofit
Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://fanyi.youdao.com/") .build();
这个baseurl和1中GET的地址和条件,共同组成了真正的url地址
3.获取服务器返回的数据
GetRequest_Interface service = retrofit.create(GetRequest_Interface.class);
Call<ResponseBody> call = service.getCall();
4.解析出你自己的数据(这里是ResponseBody,可以看看它的源码,就明白可以解析出所有的)
try { Response<ResponseBody> response = call.execute(); } catch (IOException e) { e.printStackTrace(); } Call<ResponseBody> clone = call.clone();//call只能调用一次,不然报异常 Log.e("david", "retrofit thread start " + call.toString()); clone.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { ResponseBody responseBody = response.body(); Log.e("david", "response = " + response.body().toString()); BufferedSource source = responseBody.source(); try { source.request(Long.MAX_VALUE); // Buffer the entire body. } catch (IOException e) { e.printStackTrace(); } Buffer buffer = source.buffer(); Charset charset = UTF_8; MediaType contentType = responseBody.contentType(); if (contentType != null) { try { charset = contentType.charset(charset); } catch (UnsupportedCharsetException e) { Log.e("david", ""); Log.e("david", "Couldn't decode the response body; charset is likely malformed."); Log.e("david", "<-- END HTTP"); } } Log.e("david", "content = " + buffer.clone().readString(charset)); } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { Log.e("david", "fail" + t.getMessage()); } });
如上最后打出content内容就是查询到的内容,当然这个不能运行在主线程。这只是让你看到retrofit最基本的使用,能够返回你查询的内容了。Retrofit还涉及各种注解/各种操作/异步等等,还需一步一步熟练使用
不说了,赶紧继续学习了。。。