可以可以,很强势。终于有的写了,最近研究了Retrofit2很久,可是进展非常的慢,网上的很多资料都看不太懂,因为刚开始接触,没办法下手,写个简单的Demo都没有办法实现。也不知道问题出在哪里,后来经过昨天刚加的Q群里面一些大神的指导,终于也算是有了初步的认识,相信之后学习将会轻松许多。虽然现在还只能算是新手入门,毕竟革命尚未成功,同志仍需努力啊!
那我们直接开始,先去学会如何使用,之后再花点时间去理解它吧。如果想要先去了解它的话,请往下看:
这个是它的官方文档:
http://square.github.io/retrofit/
需要中文了解的可以看看鸿洋大神的这篇博客:
http://blog.youkuaiyun.com/lmj623565791/article/details/51304204
引包:
//这个是官网最新版本的retrofit
compile 'com.squareup.retrofit2:retrofit:2.1.0'
//这里我需要使用解析的Gson包
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
然后写一个需要调用的接口
public interface HttpInterface {
@POST("api/district/getCountryList")
Call<Country> getCountrys();
}
在以上的写法中,可以看到有一个getCountrys()方法,通过@POST注解标识为post请求,@POST中所填写的value和baseUrl组成完整的路径,baseUrl在构造retrofit对象时给出。即整条链接的格式为
http://116.204.13.36:9012/api/district/getCountryList
如果是Get请求也是同样的道理。
接下来是我写的一个 Retrofit工具类。
package com.gxuwz.retrofitdemo;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Retrofit工具类
* author:hkq
* Date:16/7/29 下午3:40
* 单例模式
*/
public class RetrofitHttp {
private static final String BaseUrl = "http://116.204.13.36:9012/";
//网络请求的接口
private static HttpInterface singleton;
//全局变量配置OkHttpClient
private static OkHttpClient mOkHttpClient;
//单例模式得到网络请求接口的变量
public static HttpInterface getRetrsofit() {
if (singleton == null) {
synchronized (RetrofitHttp.class) {
singleton = createRetrofit().create(HttpInterface.class);
}
}
return singleton;
}
private static Retrofit createRetrofit() {
if (BuildConfig.DEBUG) {
OkHttpClient.Builder builder = new OkHttpClient().newBuilder()
.connectTimeout(10, TimeUnit.SECONDS)//设置超时时间
.readTimeout(10, TimeUnit.SECONDS)//设置读取超时时间
.writeTimeout(10, TimeUnit.SECONDS);//设置写入超时时间
//此处设置的是自定义的缓存大小以及位置
// int cacheSize = 10 * 1024 * 1024; // 10 MiB
// Cache cache = new Cache(App.getContext().getCacheDir(), cacheSize);
// builder.cache(cache);
mOkHttpClient = builder.build();
}
//初始化Retrofit
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BaseUrl)//设置baseUrl
.addConverterFactory(GsonConverterFactory.create())//设置了GsonConverterFactory完成对象的转化。
.client(mOkHttpClient)
.build();
return retrofit;
}
}
里面也写了一些注释,一些需要的步骤。然后我们就可以在需要的地方使用了。例如在activity中:
HttpInterface retrofit = RetrofitHttp.getRetrsofit();
retrofit.getCountrys().enqueue(new Callback<Country>() {
@Override
public void onResponse(Call<Country> call, Response<Country> response) {
Log.e("hkq", "hkq>>onResponse>>" +response.body().toString());
}
@Override
public void onFailure(Call<Country> call, Throwable t) {
Log.e("hkq", "hkq>>onFailure>>" + t.toString());
}
});
在这里特别是要注意一个问题,也是困住我好久的一个问题,因为自己并没有规范的接口,随便找的一个。而且在这里必须要注意一点:
如果需要返回的是javabean的类,在我们刚才到入的Gson包中已经可以实现,并且在.addConverterFactory(GsonConverterFactory.create()),设置了GsonConverterFactory完成对象的转化。所以我们需要返回解析后的实体类时,Call<Country> getCountrys();
Call的T必须要是实体类,在返回得到的参数中response.body()
皆为得到的结果。
注意要有实体类:
package com.gxuwz.retrofitdemo;
import java.util.List;
/**
* Created by FR on 2016/7/28.
*/
public class Country {
/**
* code : 0
* msg :
*/
private int code;
private String msg;
/**
* countryId : 45
* countryName : 中国
*/
private List<DataBean> data;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public List<DataBean> getData() {
return data;
}
public void setData(List<DataBean> data) {
this.data = data;
}
public static class DataBean {
private int countryId;
private String countryName;
public int getCountryId() {
return countryId;
}
public void setCountryId(int countryId) {
this.countryId = countryId;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
@Override
public String toString() {
return "DataBean{" +
"countryId=" + countryId +
", countryName='" + countryName + '\'' +
'}';
}
}
@Override
public String toString() {
return "Country{" +
"code=" + code +
", msg='" + msg + '\'' +
", data=" + data +
'}';
}
}
如果我们只要获取请求之后得到的字符串String类型,那好,此时我们的接口就有变化了。
public interface HttpInterface {
@POST("api/district/getCountryList")
Call<ResponseBody> getCountrys();
}
Call的T必须要是ResponseBody类,然后再回调onResponse方法里必须是
response.body().string()
才是需要的字符串
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
Log.e("hkq", "hkq>>onResponse>>" +response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
到此,告一段落。之前特别需要注意的地方都是我自己曾经踩过的坑,大家就不要再往下跳了。这一次的我们只简单的学习初步的不带参数的请求,之后我会先去好好学习其他的请求、上传等方式之后再做总结。这之后的博客我打算就目前比较流行的一个基于Dagger+RxJava+Retrofit2的MVP开发模式进行。一边学习一边进行总结。结尾附上一张图聊以表达最近的心态。