Retrofit2 应用
开始使用Retrofit
-
基本使用介绍
不啰嗦,直接看:Retrofit官网
项目实际中的问题点
-
添加公共请求参数
-
使用okhttp拦截器
-
根据请求类型分别添加参数
/** * OkHttp 拦截器,请求加上基本参数 */ public final class RequestInterceptor implements Interceptor { @Override public Response intercept(@NonNull Chain chain) throws IOException { Request request = chain.request(); String method = request.method(); Map<String, Object> basicParamMap = HttpFactory.getBasicParamMap(); if ("GET".equals(method)) { //GET请求 HttpUrl url = request.url(); HttpUrl.Builder urlbuilder = url.newBuilder(); for (String key : basicParamMap.keySet()) { urlbuilder.addQueryParameter(key, String.valueOf(basicParamMap.get(key))); } request = request.newBuilder().url(urlbuilder.build()).build(); } if ("POST".equals(method)) { //POST请求 if (request.body() instanceof FormBody) { FormBody formBody = (FormBody) request.body(); FormBody.Builder bodyBuilder = new FormBody.Builder(); if (formBody != null) { for (int i = 0; i < formBody.size(); i++) { bodyBuilder.add(formBody.encodedName(i), formBody.encodedValue(i)); } } if (basicParamMap != null) { for (String key : basicParamMap.keySet()) { bodyBuilder.add(key, String.valueOf(basicParamMap.get(key))); } } request = request.newBuilder().post(bodyBuilder.build()).build(); } } return chain.proceed(request); }
-
直接在url后面拼接基本参数
这种情况就不需要区分GET还是POST请求了,比较方便,但是要注意后台是如何获取请求参数的
/** * OkHttp 拦截器,请求加上基本参数 * 基本参数拼接到url后面 */ public final class RequestInterceptor implements Interceptor { @Override public Response intercept(@NonNull Chain chain) throws IOException { Request request = chain.request(); Map<String, Object> basicParamMap = HttpFactory.getBasicParamMap(); HttpUrl url = request.url(); HttpUrl.Builder urlbuilder = url.newBuilder(); for (String key : basicParamMap.keySet()) { urlbuilder.addQueryParameter(key, String.valueOf(basicParamMap.get(key))); } request = request.newBuilder().url(urlbuilder.build()).build(); return chain.proceed(request); } }
-
封装请求参数对象
/**
* App基础请求参数
*/
@Keep
public class BaseParam {
@JSONField(name = "app_key")
public String appKey = "appKey";
@JSONField(name = "device_type")
public String deviceType = "Android";
@JSONField(name = "version_code")
public String versionCode = "1";
@JSONField(name = "oauth_token")
public String oauthToken = "token";
}
/**
* 登录请求参数
*/
@Keep
public class LoginParam extends BaseParam {
@JSONField(name = "username")
public String name;
@JSONField(name = "password")
public String pwd;
}
/**
* 账户接口
*/
public interface AccountService {
@POST(ApiConfig.LOGIN_DOLOGIN)
Single<BaseResponse<LoginResponse>> login(@Body LoginParam param);
}
-
封装请求参数map
//略