一、小牛初试
1.在Build.Gradle中导入Retorfit的第三方依赖
implementation 'com.squareup.retrofit2:retrofit:2.9.0'//更高版本请在Github上查看
2.创建接口
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Query;
public interface HttpBinService {
@POST("post") //POST方法使用POST
@FormUrlEncoded //使用表单方式提交填写@FormUrlEncoded
Call<ResponseBody> post(@Field("username") String username, @Field("password")String pwd);
//post方式请求,字段用Field "username"会由username参数替换补充到url
@GET("get")
Call<ResponseBody> get(@Query("username") String username, @Query("password") String pwd);
//get方式请求,字段用Query
@HTTP(method="GET",path="get",hasBody = false)
//path表示选择上边的其中一个,hasbody请求体默认为false,因为get不需要请求体。
Call<ResponseBody> http(@Query("username") String username, @Query("password") String pwd);
}
3.基本的初始化
//创建变量
private Retrofit retrofit;
private HttpBinService httpBinService;
//初始化
retrofit = new Retrofit.Builder().baseUrl("https://www.httpbin.org/").build();
httpBinService=retrofit.create(HttpBinService.class);
Call<ResponseBody> call= httpBinService.post("lance","123");
//Call<ResponseBody> call= httpBinService.get("lance","123");
//Call<ResponseBody> call= httpBinService.http("lance","123");
4.调用
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
Log.d("msg",response.body().string()+"");
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
二、注解的说明
方法注解:@GET @POST @PUT @DELETE @PATH @HEAD @OPTIONS @HTTP
标记注解:@FormUrlEncoded @Multipart @Streaming
参数注解:@Query @QueryMap @Body @Field @FieldMap @Part @PartMap
其他注解:@Path @Header @Headers @Url
@HTTP
在“一、小牛初试”中已经有案例。method选择get或者post,path表示选择之前已经写好的哪个接口来实现,hasbody表示是否有请求体(默认是false),我们get是没有请求体的。
@Multipart 和@Steaming 用于文件下载
@QueryMap @FieldMap用于多个参数请求
1.现在接口中布置:
@GET("get")
Call<ResponseBody> get(@QueryMap Map<String,String> map);
2.初始化
private HashMap<String,String> param=new HashMap<>();
param.put("username","lance");
param.put("password","123");
Call<ResponseBody> call=httpBinService.get(param);
3.请求
按照以前正常请求就可以
@Body
1.布置接口
@POST("post")
//@FormUrlEncoded 有@Body注解在这里不需要添加,
Call<ResponseBody> postBody(@Body RequestBody responseBody);
2.初始化
FormBody formBody=new FormBody.Builder()
.add("username","lucan")
.add("password","123")
.build();
3.调用
new Thread(new Runnable() {
@Override
public void run() {
try {
Response<ResponseBody> response=httpBinService.postBody(formBody).execute();
Log.d("msg",response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
@Path
1.布置接口
@POST("{id}") //用参数id替换到"{id}"
Call<ResponseBody> path(@Path("id") String id);
2.调用:
new Thread(new Runnable() {
@Override
public void run() {
try {
//实际请求到的是"https://www.httpbin.org/post"
Response<ResponseBody> response=httpBinService.path("post").execute();
Log.d("msg",response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
@Header 表示请求头
1.布置接口:
@POST("{id}")
Call<ResponseBody> path(@Path("id") String id, @Header("os") String os);
2.调用
new Thread(new Runnable() {
@Override
public void run() {
try {
//实际请求到的是"https://www.httpbin.org/post"
Response<ResponseBody> response=httpBinService.path("post","Android").execute();
Log.d("msg",response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
@Headers
1.布置接口
@Headers({"os:Android","version:1"})
@POST("post")
Call<ResponseBody> postwithheaders();
2.调用
new Thread(new Runnable() {
@Override
public void run() {
Call<ResponseBody> call=httpBinService.postwithheaders();
try {
Log.d("msg",call.execute().body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
调用结果
@Url
1.布置接口:
@POST
Call<ResponseBody> posturl(@Url String url);
2.调用:
new Thread(new Runnable() {
@Override
public void run() {
try {
Response<ResponseBody> response=httpBinService.posturl("https://www.httpbin.org/post").execute();
Log.d("msg",response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
三、Retrofit转换器
? ? ? ? 转换器是什么,是为了接收gson数据后快速进行转换。
1.导入Gson
implementation 'com.google.code.gson:gson:2.9.0'
2.去wanandroid找开放API,试着拉取数据
https://www.wanandroid.com/user/login
方法:POST
参数:
username,password
3..定义接口
????????
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;
public interface WanandroidService {
@POST("user/login")
@FormUrlEncoded
Call<ResponseBody> login(@Field("username") String username, @Field("password")String password);
}
4.调用
public class WanAndroidUnitTest {
Retrofit retrofit= new Retrofit.Builder().baseUrl("https://www.wanandroid.com/").build();
WanandroidService wanandroidService=retrofit.create(WanandroidService.class);
@Test
public void login() throws IOException {
Call<ResponseBody> call=wanandroidService.login("lanceedu","123123");
Response<ResponseBody> response=call.execute();
String result=response.body().string();
System.out.println(result);
}
}
5.result回调
{"data":{"admin":false,"chapterTops":[],"coinCount":4500,"collectIds":[17188,18965,20087,19623],"email":"","icon":"","id":86459,"nickname":"lanceedu","password":"","publicName":"lanceedu","token":"","type":0,"username":"lanceedu"},"errorCode":0,"errorMsg":""}
6.我们创建javabean
如果一个一个的创建很麻烦,
这时我们把json复制下来,百度搜索“bejson”,打开在线JSON校验格式化工具(Be JSON)网址。在json工具里有个转换为java类
?然后就可以看到接过了,可以改文件名和包名,下载下来导入项目,或者自己创建文件复制粘贴过去。
7.因为上边只是查看数据,所以我们现在要将他自行赋值给BaseReponse这个Bean,
我们要创建一个新的接口WanandroidService2
import com.example.***.beans.BaseResponse;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;
public interface WanandroidService2 {
@POST("user/login")
@FormUrlEncoded //注意这里的Call<ResponseBody> 替换成了 Call<BaseResponse>
Call<BaseResponse> login(@Field("username") String username, @Field("password")String password);
}
8.为了能把以前的ResponseBody替换成BaseResponse的JavaBean,我们需要导入Gson的转换器,。
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
9.之后运行Test
@Test
public void loginConvert() throws IOException {
Retrofit retrofit2= new Retrofit.Builder().
baseUrl("https://www.wanandroid.com/")
.addConverterFactory(GsonConverterFactory.create()).build();
WanandroidService2 wanandroidService2=retrofit2.create(WanandroidService2.class);
Call<BaseResponse> call=wanandroidService2.login("lanceedu","123123");
Response<BaseResponse> response=call.execute();
BaseResponse baseResponse=response.body();
System.out.println(baseResponse);
}
10.查看结果
BaseResponse{data=Data{admin=false, chapterTops=[], coinCount=4536, collectIds=[17188, 18965, 20087, 19623], email='', icon='', id=86459, nickname='lanceedu', password='', publicName='lanceedu', token='', type=0, username='lanceedu'}, errorCode=0, errorMsg=''}
如上所示,我们收到了一个BaseResponse的JavaBean对象。
四、Retrofit的适配器
1.导入
? ? ? ?
implementation 'com.squareup.retrofit2:adapter-rxjava3:2.9.0'
implementation 'io.reactivex.rxjava3:rxandroid:3.0.0'
2.创建接口
先登录,再查找收藏的文章
@POST("user/login")
@FormUrlEncoded
Flowable<BaseResponse> login2(@Field("username") String username, @Field("password")String password);
@GET("lg/collect/list/{pageNum}/json")
Flowable<ResponseBody> getArticle(@Path("pageNum") int pageNum);
3.调用
Map<String,List<Cookie>> cookies =new HashMap<>();
@Test
public void rxjavaTest() {
Map<String,List<Cookie>> cookies =new HashMap<>();
Retrofit retrofit3= new Retrofit.Builder()
.baseUrl("https://www.wanandroid.com/")
//先配置cookie
.callFactory(new OkHttpClient.Builder().cookieJar(new CookieJar() {
@Override
public void saveFromResponse(HttpUrl url, List<Cookie> list) {
cookies.put(url.host(),list);
}
@Override
public List<Cookie> loadForRequest(HttpUrl url) {
List<Cookie> cookie=cookies.get(url.host());
return cookie==null?new ArrayList<>() : cookie;
}
}).build())
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava3CallAdapterFactory.create()).build();
WanandroidService2 wanandroidService2=retrofit3.create(WanandroidService2.class);
wanandroidService2.login2("lanceedu","123123")
//在登陆后调用
.flatMap(new Function<BaseResponse, Publisher<ResponseBody>>() { //在请求完登录后查看收藏的文章
@Override
public Publisher<ResponseBody> apply(BaseResponse baseResponse) throws Throwable {
return wanandroidService2.getArticle(0);
}
})
.observeOn(Schedulers.io())
.subscribeOn(Schedulers.newThread()) //安卓中请使用AndroidScheulers.newThread()
.subscribe(new Consumer<ResponseBody>() {
@Override
public void accept(ResponseBody baseResponse) throws Throwable {
System.out.println(baseResponse.string());
}
});
while(true){}
}
|