比较以上两种格式,发现格式不对.传给后台时,总是报参数错误的异常.
解决办法:定义一个对象继承自okhttp3.RequestBody
public class DefaultRequestBody extends okhttp3.RequestBody{
public List list;
@Nullable
@Override
public MediaType contentType() {
return MediaType.parse("application/json; charset=utf-8");
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
}
}
通过Retrofit定义请求接口API
@FormUrlEncoded@POST("url")
Observable request(@body DefaultRequestBody body);
打开PostMan,输入url,输入请求参数,选择Body,选择raw,选择JSON(application/json)
1
输入json格式的参数,点击右侧的[code]查看,选择[java ok http],如图
2
关键的代码:
MediaType mediaType = MediaType.parse("application/json"); RequestBody body = RequestBody
.create(mediaType, "{"list": ["xxx","yyy"]}");
create方法的第二个参数就是我们的对象DefaultRequestBody转换后的json字符串.
//Gson转换自动处理了字符串数组,不会出现上面那种value格式错误String json = new org.google.Gson().toJson(new DefaultRequestBody());
上面定义的接口request API中传入的是对象DefaultRequestBody,我们在okHttp的拦截器里做转换
public class DefaultIntercept extends okhttp3.Intercept{
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
RequestBody requestBody = request.body();
if(requestBody instanceof DefaultRequestBody){
DefaultRequestBody defaultBody = (DefaultRequestBody)requestBody;
String json = new Gson().toJson(defaultBody);
MediaType mediaType = MediaType.parse("application/json");
//生成RequestBody
RequestBody body = RequestBody.create(mediaType,json);
//传递body,重新生成request请求
request = request.newBuilder().post(body).build();
}
return chain.proceed(request);
}
}
解决了传递字符串数组的问题
以上就介绍了JAVA的相关知识,希望对JAVA有兴趣的朋友有所帮助。了解更多内容,请关注职坐标编程语言JAVA频道!