添加gradle:
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
A type-safe HTTP client for Android and Java
这是官网对retrofix的介绍。
retrofix出自Square公司,是一个很好网络请求框架。看了源码之后,该框架满满的都是设计模式,满满的都是解偶,这个框架扩展性非常的强,膜拜啊。
retrofix2的包结构:
可以看到只有那么的几个类,因为retrofix把请求的任务交给了OkHttp。
retrofix2:
retrofix2.http:该包下定义了很多注解。通过这些注解来表明请求的方式是什么方式,URL怎么处理等。
常用的注解:
@GET():表示发送Get的请求。
@POST():表示Post请求。
@Query();发送请求配置一个参数
@QueryMap();发送请求配置多个参数。
@Multipart();表示发送MultiPart数据。
@Part();发送MultiPart数据时,通过该注解来定义每一个文件。
@PartMap();发送MultiPart数据时,通过该注解来定义多个文件。
我使用了聚合数据新闻的一个接口:
接口:http://op.juhe.cn/onebox/news/query
AppKey:ea2ee38eb5d582931b66e927eff35b24
定义一个接口NewsService:
public interface NewsServive {
@GET("/onebox/news/query")
Call<NewsInfo> newsListByGetMethod(@QueryMap Map<String,String> paramsMap);
}
使用retrofix发送请求这样定义一个接口就可以了,神奇吧。
注解说明:
@GET,表示发送一个get请求,值为请求地址(域名以后)。
@QueryMap:请求参数。也可以用@Query,这里我们有两个参数。写法为:
public interface NewsServive {
@GET("/onebox/news/query")
Call<NewsInfo> newsListByGetMethod(@Query("q") String q ,@Query("key") String key);
}
@Query注解的值,q,key是对应请求的字段名。
如果发送Post请求,把注解@GET改为@POST就可以了,@QueryMap和@Query注解的用法一样。
public interface NewsServive {
@POST("/onebox/news/query")
Call<NewsInfo> newsListByGetMethod(@QueryMap Map<String,String> paramsMap);
}
public interface NewsServive {
@POST("/onebox/news/query")
Call<NewsInfo> newsListByGetMethod(@Query("q") String q ,@Query("key") String key);
}
Activity:
public class TestRetrofixActivity extends AppCompatActivity {
private final static String BASE_URL = "http://op.juhe.cn";
private final static int REQ_OK = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_retrofix);
reqServer();
}
private void reqServer() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL) //请求地址的域名
.addConverterFactory(GsonConverterFactory.create())//把请求返回的数据解析我们关系的格式,这里我们通过Gson来解析返回的数据
.client(new OkHttpClient())
.build();
NewsServive newsServive = retrofit.create(NewsServive.class);
Map paramsMap = getParamsMap(); //获取请求参数
Call<NewsInfo> newsInfoCall = newsServive.newsListByGetMethod(paramsMap);
//发送异步的请求
newsInfoCall.enqueue(new Callback<NewsInfo>() {
@Override
public void onResponse(Call<NewsInfo> call, Response<NewsInfo> response) {
NewsInfo newsInfo = response.body();
if(newsInfo.getError_code() == REQ_OK){
for (NewsInfo.ResultBean info : newsInfo.getResult()){
Log.e("tag","-----> info = " + info.toString());
}
}else{
Log.e("tag","----> reason = " + newsInfo.getReason());
}
}
@Override
public void onFailure(Call<NewsInfo> call, Throwable t) {
Log.e("tag","-----> error = " + t.getMessage());
}
});
}
private Map getParamsMap() {
Map<String,String> map = new HashMap<>();
map.put("q","百度竞价");
map.put("key","ea2ee38eb5d582931b66e927eff35b24");
return map;
}
}
可以看到retrofix使用起来非常的简单,就不过多解释了。
下面我们来看看,使用retrofix上传图片:
定义接口:
public interface ImageUploadSerivce {
@Multipart
@POST("/upload")
Call<String> uploadImage(@Part("fileName") RequestBody image);
}
如果有多个文件需要上传,使用注解@PartMap,也可以使用多个@Part注解,如下:
public interface ImageUploadSerivce {
@Multipart
@POST("/upload")
Call<String> uploadImage(@PartMap Map<String,RequestBody> params);
}
public interface ImageUploadSerivce {
@Multipart
@POST("/upload")
Call<String> uploadImage(@Part("fileName") RequestBody image ,@Part("file2") RequestBody image2);
}
Activity:
public class ImageUploadActivity extends AppCompatActivity {
private static final String BASE_URL = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_upload);
uploadImage();
}
private void uploadImage() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL) //请求地址的域名
.addConverterFactory(GsonConverterFactory.create())//把请求返回的数据解析我们关系的格式,这里我们通过Gson来解析返回的数据
.client(new OkHttpClient())
.build();
ImageUploadSerivce imageUploadSerivce = retrofit.create(ImageUploadSerivce.class);
File file = new File("image.png");
RequestBody imgBody = RequestBody.create(MediaType.parse("multipart/form-data"),file);
Call<String> call = imageUploadSerivce.uploadImage(imgBody);
call.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
Log.d("tag","-------> response = " + response.message());
}
@Override
public void onFailure(Call<String> call, Throwable t) {
Log.d("tag","-------> error = " + t.getMessage());
}
});
}
}
retrofix使用起来还是很简单的,就不多解释了。
如有什么问题,希望大家多多指正。谢谢。
END