Retrofit
Retrofit之Converter
应用程序通过 Retrofit 请求网络,实际上是使用 Retrofit 接口层封装请求参数、Header、Url 等信息,之后由 OkHttp 完成后续的请求操作,在服务端返回数据之后,OkHttp 将原始的结果交给 Retrofit,后者根据用户的需求对结果进行解析的过程。
在Retrofit中, 不管是发送数据或是接收数据, 最基本都是通过OKHttp的RequestBody和ResponseBody来实现,但是通常为了方便,我们在定制协议的时候,不会直接使用原始的RequestBody或是ResponseBody,因此,在Retrofit中,我们就需要对它进行转换。
Converter用于转换数据,例如,请求服务器时,经常会把对象转换成json格式,或者xml,收到服务器返回的文本时,又会需要转换成对象,或者String等。
手动VS自动 (进行数据转换)
BaseResponse
/**
* Copyright 2021 bejson.com
*/
package com.enjoy.networkdemo.bean;
/**
* Auto-generated: 2021-02-06 15:44:25
*
* @author bejson.com (i@bejson.com)
* @website http://www.bejson.com/java2pojo/
*/
public class BaseResponse {
private Data data;
private int errorCode;
private String errorMsg;
public void setData(Data data) {
this.data = data;
}
public Data getData() {
return data;
}
public void setErrorCode(int errorCode) {
this.errorCode = errorCode;
}
public int getErrorCode() {
return errorCode;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
public String getErrorMsg() {
return errorMsg;
}
@Override
public String toString() {
return "BaseResponse{" +
"data=" + data +
", errorCode=" + errorCode +
", errorMsg='" + errorMsg + '\'' +
'}';
}
}
Data
/**
* Copyright 2021 bejson.com
*/
package com.enjoy.networkdemo.bean;
import java.util.List;
/**
* Auto-generated: 2021-02-06 15:44:25
*
* @author bejson.com (i@bejson.com)
* @website http://www.bejson.com/java2pojo/
*/
public class Data {
private boolean admin;
private List<String> chapterTops;
private int coinCount;
private List<Integer> collectIds;
private String email;
private String icon;
private long id;
private String nickname;
private String password;
private String publicName;
private String token;
private int type;
private String username;
public void setAdmin(boolean admin) {
this.admin = admin;
}
public boolean getAdmin() {
return admin;
}
public void setChapterTops(List<String> chapterTops) {
this.chapterTops = chapterTops;
}
public List<String> getChapterTops() {
return chapterTops;
}
public void setCoinCount(int coinCount) {
this.coinCount = coinCount;
}
public int getCoinCount() {
return coinCount;
}
public void setCollectIds(List<Integer> collectIds) {
this.collectIds = collectIds;
}
public List<Integer> getCollectIds() {
return collectIds;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getIcon() {
return icon;
}
public void setId(long id) {
this.id = id;
}
public long getId() {
return id;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getNickname() {
return nickname;
}
public void setPassword(String password) {
this.password = password;
}
public String getPassword() {
return password;
}
public void setPublicName(String publicName) {
this.publicName = publicName;
}
public String getPublicName() {
return publicName;
}
public void setToken(String token) {
this.token = token;
}
public String getToken() {
return token;
}
public void setType(int type) {
this.type = type;
}
public int getType() {
return type;
}
public void setUsername(String username) {
this.username = username;
}
public String getUsername() {
return username;
}
@Override
public String toString() {
return "Data{" +
"admin=" + admin +
", chapterTops=" + chapterTops +
", coinCount=" + coinCount +
", collectIds=" + collectIds +
", email='" + email + '\'' +
", icon='" + icon + '\'' +
", id=" + id +
", nickname='" + nickname + '\'' +
", password='" + password + '\'' +
", publicName='" + publicName + '\'' +
", token='" + token + '\'' +
", type=" + type +
", username='" + username + '\'' +
'}';
}
}
WanAndroidService
package com.enjoy.networkdemo;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
public interface WanAndroidService {
@POST("user/login")
@FormUrlEncoded
Call<ResponseBody> login(@Field("username") String username, @Field("password") String pwd);
}
WanAndroidService2
package com.enjoy.networkdemo;
import com.enjoy.networkdemo.bean.BaseResponse;
import io.reactivex.rxjava3.core.Flowable;
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.Path;
public interface WanAndroidService2 {
@POST("user/login")
@FormUrlEncoded
Call<BaseResponse> login(@Field("username") String username, @Field("password") String pwd);
@POST("user/login")
@FormUrlEncoded
Flowable<BaseResponse> login2(@Field("username") String username, @Field("password") String pwd);
@GET("lg/collect/list/{pageNum}/json")
Flowable<ResponseBody> getArticle(@Path("pageNum") int pageNum);
}
WanAndroidUnitTest
package com.enjoy.networkdemo.retrofit;
import com.enjoy.networkdemo.CookieUnitTest;
import com.enjoy.networkdemo.HttpbinService;
import com.enjoy.networkdemo.WanAndroidService;
import com.enjoy.networkdemo.WanAndroidService2;
import com.enjoy.networkdemo.bean.BaseResponse;
import com.google.gson.Gson;
import org.jetbrains.annotations.NotNull;
import org.junit.Test;
import org.reactivestreams.Publisher;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.core.Scheduler;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.functions.Function;
import io.reactivex.rxjava3.schedulers.Schedulers;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
public class WanAndroidUnitTest {
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://www.wanandroid.com/").build();
WanAndroidService wanAndroidService = retrofit.create(WanAndroidService.class);
@Test
public void loginTest() throws IOException {
Call<ResponseBody> call =
wanAndroidService.login("lanceedu", "123123");
Response<ResponseBody> response = call.execute();
String result = response.body().string();
System.out.println(result);
//手动进行数据转换
BaseResponse baseResponse = new Gson().fromJson(result, BaseResponse.class);
System.out.println(baseResponse);
}
//自动进行数据转换
Retrofit retrofit2 = new Retrofit.Builder()
.baseUrl("https://www.wanandroid.com/")
.addConverterFactory(GsonConverterFactory.create()) //添加转换器
.build();
WanAndroidService2 wanAndroidService2 = retrofit2.create(WanAndroidService2.class);
@Test
public void loginConvertTest() throws IOException {
Call<BaseResponse> call = wanAndroidService2.login("lanceedu", "123123");
Response<BaseResponse> response = call.execute();
BaseResponse baseResponse = response.body();
System.out.println(baseResponse);
}
}
输出
{"data":{"admin":false,"chapterTops":[],"coinCount":0,"collectIds":[17188,18965],"email":"","icon":"","id":86459,"nickname":"lanceedu","password":"","publicName":"lanceedu","token":"","type":0,"username":"lanceedu"},"errorCode":0,"errorMsg":""}
BaseResponse{data=Data{admin=false, chapterTops=[], coinCount=0, collectIds=[17188, 18965], email='', icon='', id=86459, nickname='lanceedu', password='', publicName='lanceedu', token='', type=0, username='lanceedu'}, errorCode=0, errorMsg=''}
Process finished with exit code 0