我构建了如下请求:
public static ApiBuilder newInstance(){
GsonBuilder gsonBuilder = new GsonBuilder()
.registerTypeAdapter(Boolean.class, booleanAsIntAdapter)
.registerTypeAdapter(boolean.class, booleanAsIntAdapter)
.registerTypeAdapter(Date.class, (JsonDeserializer<Date>) (json, typeOfT, context)
-> new Date(Long.valueOf(json.getAsString())));
OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(180, TimeUnit.SECONDS);
client.setReadTimeout(240, TimeUnit.SECONDS);
String url = MyApplicationConfiguration.getInstance().get("urlofservice");
RestAdapter restAdapter = new RestAdapter.Builder()
.setRequestInterceptor(
request -> {
request.addHeader(deviceIdHeader, MyApplication.getDeviceId());
}
).setConverter(new GsonConverter(gsonBuilder.create()))
.setEndpoint(url)
.setClient(new OkClient(client)).build();
restAdapter.setLogLevel(RestAdapter.LogLevel.FULL);
return restAdapter.create(ApiExtendedValidation.class);
}
private static final TypeAdapter<Boolean> booleanAsIntAdapter = new TypeAdapter<Boolean>() {
@Override
public void write(JsonWriter out, Boolean value) throws IOException {
if (value == null) {
out.nullValue();
} else {
out.value(value);
}
}
@Override
public Boolean read(JsonReader in) throws IOException {
JsonToken peek = in.peek();
switch (peek) {
case BOOLEAN:
return in.nextBoolean();
case NULL:
in.nextNull();
return null;
case NUMBER:
return in.nextInt() != 0;
case STRING:
return Boolean.parseBoolean(in.nextString());
default:
throw new IllegalStateException("Expected BOOLEAN or NUMBER but was " + peek);
}
}
};
API接口为:
@Headers("Content-Type: application/json")
@POST("/validate")
Observable<QRValidateResponse> validateQRCode(@Body QRRequest request);
这QRRequest
是一个对象,它包含一个带有 Base64 ecnoded 字符串的 String 字段
编码示例
byte[] data = rawResult.getText().getBytes(StandardCharsets.ISO_8859_1);
String encodedResult = Base64.encodeToString(data, Base64.DEFAULT);
对象示例
request{
"lang": "EN",
"content": "SGVsbG8gV29ybGQh="
}
当 Retrofit 执行请求时,request.content
变化如下:
SGVsbG8gV29ybGQh\u003d
服务器无法识别内容,因此它的响应是错误的。
为什么在请求期间内容会发生变化?有没有办法避免它?
解决方案
存在与使用 Gson 相关的转义错误。根据这篇文章,解决了将其添加disableHtmlEscaping()
到 GsonBuilder 的问题。