1. 添加本地缓存时,post 方式的请求不缓存。
2. @Body 方式提交数据时,会转成 json 形式提交, 而不是键值对。
自定义 GsonConverterFactory ,主要是 GsonRequestBodyConverter 类。
final class GsonRequestBodyConverter<T> implements Converter<T, RequestBody> { private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8"); private static final Charset UTF_8 = Charset.forName("UTF-8"); private final Gson gson; private final TypeAdapter<T> adapter; GsonRequestBodyConverter(Gson gson, TypeAdapter<T> adapter) { this.gson = gson; this.adapter = adapter; } @Override public RequestBody convert(T value) throws IOException { Buffer buffer = new Buffer(); buffer.read(UrlFormedUtils.getFormUrlEncoded(value).getBytes()); return RequestBody.create(MEDIA_TYPE, buffer.readByteString()); }}
// 把对象转为url 键值对。
public static <T> String getFormUrlEncoded(T t){ String cls1 = t.getClass().getName(); StringBuffer sb = new StringBuffer(); try { Class<?> cls = Class.forName(cls1); Field[] fields = cls.getDeclaredFields(); for(Field field:fields){ if (field.isSynthetic()) { continue; } if (field.getName().equals("serialVersionUID")) { continue; } field.setAccessible(true); if(field.get(t)!=null && !TextUtils.isEmpty(field.get(t).toString())){ sb.append("&").append(field.getName()).append("=").append(field.get(t)); } } Class<?> superCls = cls.getSuperclass(); if(!superCls.getSimpleName().equals("Object")){ fields = superCls.getDeclaredFields(); for(Field field:fields){ if (field.isSynthetic()) { continue; } if (field.getName().equals("serialVersionUID")) { continue; } field.setAccessible(true); if(field.get(t)!=null && !TextUtils.isEmpty(field.get(t).toString())){ sb.append("&").append(field.getName()).append("=").append(field.get(t)); } } } return sb.toString(); } catch (Exception e) { e.printStackTrace(); } return "";}
时间: 2024-10-26 11:11:15