Retrofit2已经被不知多少人写过了,搜索引擎一大堆。
这里只对Retrofit2进行实战(Get,Post),不做概述。
Retrofit注解详解
- HTTP请求方法 注解
- 标记类 注解
- 参数类 注解
一 、Retrofit依赖导入
Retrofit封装了okthhp,只导入Retrofit就可以了,不用在导入okhttp了。
implementation 'com.squareup.retrofit2:retrofit:2.5.0'//Retrofit依赖
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'//可选依赖,解析json字符所用
二 、Retrofit使用
- 1、定义一个server接口
public interface MyServer {
// 定义URL 必须以反斜杠结尾 Retrofit 是一个 RESTful 的 HTTP 网络请求框架的封装
//http://192.168.1.112/app/?a=1 会自动截掉?a=1 使url符合RESTful 风格
String baseURL = "http://192.168.1.112/app/";
//@GET("xxx") 在url后边拼接xxx
//@GET("?a=1")
//服务器接收的url是 : http://192.168.1.112/app/?a=1
//@GET("xxx?a=1")
//服务器接收的url是 : http://192.168.1.112/app/xxx?a=1
//除了以上办传参以外 还可以在方法中接收参数拼接到url上
//以下get方法 服务器接收的是 :http://192.168.1.112/app/xxx?page=1&area=2
@GET("xxx")
Call<ResponseBody> getNewBook(@Query("page") String page ,@Query("area") String area);
// 定义 post 请求
//post请求需要使用 标记类注解 FormUrlEncoded,对参数进行编码
//@POST("xxx") 在url后边拼接xxx
//服务器接收的url是 : http://192.168.1.112/app/xxx
@POST("xxx")
@FormUrlEncoded
Call<ResponseBody> postData2(@FieldMap Map<String,Object> map);
// PUT、DELETE 是应对不同业务逻辑的,和GET使用方法类似
}
- 2、构建retrofit对象
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(MyServer.baseURL)
.build();
- 3、创建接口对象
MyServer myServer = retrofit.create(MyServer.class);
- 4、获取Call对象
//GET
Call<ResponseBody> call = myServer.getNewBook("1","2");
//POST
Map<String,Object> map = new HashMap<>();
Call<ResponseBody> call = myServer.postData2(map);
- 5、Call对象执行http请求
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call,Response<ResponseBody> response) {
try {
String result = response.body().string();
Log.e("-----", "onResponse: "+result);
//不用切换主线程了,因为Retrofit帮我们切过了
//okHttpClient需要自己切换主线程
//tv.setText(result);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("-----", "onFailure: "+t.getMessage());
}
});
深入的童鞋可以转到:你真的会用Retrofit2吗?Retrofit2完全教程