前言:
在Android项目开发中,网络请求如今常使用OkHttp + Retrofit + RxJava + JSON请求体 的请求架构。
后端使用SpringMVC的架构,这个架构需要接收JSON格式的请求体(如今大多数都是JSON),移动端则需要对RequestBody进行JSON化的处理。
解决方案:
将RequestBody请求体转化为JSON请求体,在请求体内加入固定参数。
主要思想是在创建OkHttp的时候设置拦截器,利用拦截器拦截请求体,获取请求体内容并改写重新整合到网络请求中。具体代码如下:
Interceptor addQueryParameterInterceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
Request request;
HttpUrl modifiedUrl = originalRequest.url().newBuilder()
//这个是拦截url并插入token参数
//.addQueryParameter("token", User.getUser().getToken())
.build();
RequestBody body = originalRequest.body(); // 得到请求体
Buffer buffer = new Buffer(); // 创建缓存
body.writeTo(buffer); // 将请求体内容,写入缓存
String parameterStr = buffer.readUtf8(); // 读取参数字符串
//LogUtils.e("处理前的请求体内容:",parameterStr);
//解析json(本人利用阿里的FastJSON)
JSONObject jsonObject = JSONObject.parseObject(parameterStr);
//重新加入参数(可以是任意固定参数)
jsonObject.put("token",User.getUser().getToken());
String newParameterStr = jsonObject.toString();
//LogUtils.e("处理后的请求体内容:",newParameterStr);
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), newParameterStr);
request = originalRequest.newBuilder()
//.url(modifiedUrl)
.post(requestBody)
.build();
return chain.proceed(request);
其他:
如果实现不了,首先得确定你的请求体是JSON格式的,如果不是方法如下:
/**
* @功能 将json格式转化为RequestBody格式,方便进行请求接口
*/
public static RequestBody translateJson(Object json) {
return RequestBody.create(MediaType.parse("application/json"), json.toString());
}
调用:
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("userid", 100);
...
} catch (JSONException e) {
e.printStackTrace();
}
apiStores.getInfo(translateJson(jsonObject))