OkHttpClient是这么写的:
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.connectTimeout(DEFAULT_CONNECT_TIMEOUT, TimeUnit.SECONDS)
.readTimeout(DEFAULT_READ_TIMEOUT, TimeUnit.SECONDS)
.writeTimeout(DEFAULT_WRITE_TIMEOUT, TimeUnit.SECONDS)
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request.Builder rBuilder = chain.request().newBuilder();
rBuilder.addHeader("Content-Type", "application/json; charset=UTF-8");
String idToken = PreferencesUtil.getAuthIdToken();
if (idToken != null && idToken.length() > 0) {
rBuilder.addHeader("Authorization", "Bearer " + idToken);
}
Request request = rBuilder.build();
Response response = chain.proceed(request);
return response;
}
});
添加的转换器
.addConverterFactory(FastJsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
但是在后端返回的数据中 返回的格式是Text/plain 格式, 而不是json数据, 导致返回的数据, 使用FastJson接不到数据, 就会报错, 后来google之后 发现Retrofit官方是提供了这个格式的数据解析方式的, 使用方式只要把特殊的解析方式的解析器放在前面就可以了-->>;
.addConverterFactory( ToStringConverterFactory.create())
.addConverterFactory(FastJsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
retrofit官方给的解析器https://github.com/square/retrofit/blob/master/retrofit/src/test/java/retrofit2/helpers/ToStringConverterFactory.java
具体代码如下:
public class ToStringConverterFactory extends Converter.Factory {
static final MediaType MEDIA_TYPE = MediaType.parse("text/plain");
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
Retrofit retrofit) {
if (String.class.equals(type)) {
return new Converter<ResponseBody, String>() {
@Override public String convert(ResponseBody value) throws IOException {
return value.string();
}
};
}
return null;
}
@Override public Converter<?, RequestBody> requestBodyConverter(Type type,
Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
if (String.class.equals(type)) {
return new Converter<String, RequestBody>() {
@Override public RequestBody convert(String value) throws IOException {
return RequestBody.create(MEDIA_TYPE, value);
}
};
}
return null;
}
}
网友评论