前言
Retrofit是Square公司开发的一款针对Android网络请求的框架,遵循Restful设计风格,底层基于OkHttp,获得许多使用者的好评,也是现在的主流网络请求框架。
使用好各种框架有利于我们更快的实现项目,本文主要讲解Retrofit网络框架的使用以及各种注解的注释。
一、使用
以下以访问词霸api为例,URL为“http://fy.iciba.com/ajax.php?a=fy&f=auto&t=auto&w=hello%20world”
1.添加依赖
- 在app包下的build.gradle中
dependencies {
compile 'com.squareup.retrofit2:retrofit:2.1.0'
// Retrofit库
implementation 'com.squareup.retrofit2:converter-gson:2.1.0' //GSON解析
}
- 添加 网络权限
AndroidManifest.xml*
<uses-permission android:name="android.permission.INTERNET"/>
2.创建 接收服务器返回数据 的类
使用GsonFormat生成对应的Java Bean类
{
"status":1,
"content":{
"from":"en",
"to":"zh-CN",
"vendor":"ciba",
"out":" 你好,世界",
"ciba_use":"来自机器翻译。",
"ciba_out":"",
"err_no":0
}
}
public class TranslationBean {
/**
* status : 1
* content : {"from":"en","to":"zh-CN","vendor":"ciba","out":" 你好,世界","ciba_use":"来自机器翻译。","ciba_out":"","err_no":0}
*/
private int status;
private ContentBean content;
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public ContentBean getContent() {
return content;
}
public void setContent(ContentBean content) {
this.content = content;
}
public static class ContentBean {
/**
* from : en
* to : zh-CN
* vendor : ciba
* out : 你好,世界
* ciba_use : 来自机器翻译。
* ciba_out :
* err_no : 0
*/
private String from;
private String to;
private String vendor;
private String out;
private String ciba_use;
private String ciba_out;
private int err_no;
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getVendor() {
return vendor;
}
public void setVendor(String vendor) {
this.vendor = vendor;
}
public String getOut() {
return out;
}
public void setOut(String out) {
this.out = out;
}
public String getCiba_use() {
return ciba_use;
}
public void setCiba_use(String ciba_use) {
this.ciba_use = ciba_use;
}
public String getCiba_out() {
return ciba_out;
}
public void setCiba_out(String ciba_out) {
this.ciba_out = ciba_out;
}
public int getErr_no() {
return err_no;
}
public void setErr_no(int err_no) {
this.err_no = err_no;
}
}
//定义 输出返回数据 的方法
public void show() {
Log.d("翻译:", content.out );
}
}
3.创建 用于描述网络请求 的接口
public class TransApi {
public interface ToTrans {
@GET("ajax.php?a=fy&f=auto&t=auto&w=hi%20world")
Call<TranslationBean> getCall();
// @GET注解的作用:采用Get方法发送网络请求
// getCall() = 接收网络请求数据的方法
// 其中返回类型为Call<*>,*是接收数据的类(即上面定义的TranslationBean类),返回这个类的对象
}
}
4.创建 Retrofit 实例
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://fy.iciba.com/") //网络请求的url地址
.addConverterFactory(GsonConverterFactory.create()) //数据解析器,解析json
.build();
5.创建 网络请求接口实例
// 创建 网络请求接口 的实例
TransApi request = retrofit.create(TransApi.class);
//对 发送请求 进行封装
Call<TranslationBean> call = request.getCall();
6.发送网络请求
/发送网络请求(异步)
call.enqueue(new Callback<TranslationBean>() {
//请求成功时回调
@Override
public void onResponse(Call<TranslationBean> call, Response<TranslationBean> response) {
//请求处理,输出结果
response.body().show();
}
//请求失败时候的回调
@Override
public void onFailure(Call<TranslationBean> call, Throwable throwable) {
System.out.println("连接失败");
}
});
// 发送网络请求(同步)
try {
Response<TranslationBean> response = call.execute();
} catch (IOException e) {
e.printStackTrace();
}
}
7.处理返回数据
/发送网络请求(异步)
call.enqueue(new Callback<TranslationBean>() {
//请求成功时回调
@Override
public void onResponse(Call<TranslationBean> call, Response<TranslationBean> response) {
//请求处理,输出结果
response.body().show(); //处理返回数据,这里是显示出数据
}
//请求失败时候的回调
@Override
public void onFailure(Call<TranslationBean> call, Throwable throwable) {
System.out.println("连接失败");
}
});
二、网络接口注解类型
1.请求方法
- 注解对应着Http的请求方法
@GET -> GET
@POST -> POST
@PUT -> PUT
@DELETE -> DELETE
@PATCH -> PATCH
@HEAD -> HEAD
@OPTIONS -> OPTIONS
@GET("ajax.php?a=fy&f=auto&t=auto&w=hi%20world")
Call<TranslationBean> getCall();
// @GET注解的作用:采用Get方法发送网络请求
2.标记类型
- @FormUrlEncoded —— 表示请求体是一个From表单
每个键值对需要用@Filed来注解键名,随后的对象需要提供值
@FormUrlEncoded
@POST("/form")
Call<ResponseBody> getList(@Field("type") String type);
- @Multipart —— 表示请求体是一个支持文件上传的From表单
每个键值对需要用请求参数@Part来注解键名,随后的对象是需要提供值
@Multipart
@POST("game/findgamebinsb")
Call<ResponseBody> gameList(@PartMap Map<String, RequestBody> requestBodyMap);
- @Streaming —— 表示请求的数据以流的形式返回
注意:若未使用@Streaming注解,默认会把数据全部载入内存,获取数据也是读取内存中的数据,当返回数据较大并且没有使用该注解时,会产生OOM。
@Streaming
@GET("/update_apk")
Call<ResponseBody> downloadFile(@Url String fileUrl);
3.请求参数
| 注解名称 | 作用 | 使用位置 |
|---|---|---|
| @Headers | 用于添加请求头 | 请求接口的方法上 |
| @Header | 添加不固定值的Header | 请求接口的方法参数中 |
| @Field/@FieldMap | 向Post表单中传键值对,与@FormUrlEncoded注解配合使用 | |
| @Part/@PartMap | 表单字段,与@Multipart注解配合使用,适合有文件上传的情况 | |
| @Query/@QueryMap | 用于表单字段,作用和@Field@FieldMap相同;区别:@Query和@QueryMap中的数据体现在Url上,而@Field和@FieldMap的数据是请求体,但最后生成的数据形式是一样的 | |
| @Body | 非表单请求体 | |
| @Path | URL缺省值 | |
| @URL | URL设置 |
参考自:
- 《Android 进阶之光》
- Android Retrofit 2.0 的详细 使用攻略(含实例讲解)
- Retrofit2的使用及注解分析
本文使用 mdnice 排版