在异步模式下改装调用
public void success(T t, Response rawResponse)
是转换后的响应,rawResponse是原始响应。这使您可以访问原始响应和转换后的响应。
在同步模式下,您可以获得转换后的响应 OR 原始响应
转换后的回复
@GET("/users/list")
List<User> userList();
原始回复
@GET("/users/list")
Response userList();
Response对象确实有一个获取正文的方法
TypedInput getBody()
并且改装api确实有一个可以将其转换为java对象的转换器类
Object fromBody(TypedInput body,Type type)
但我无法弄清楚如何获取Converter对象的实例
我可能能够创建Converter类的实例,但这需要知道用于创建RestAdapter的Gson对象,我可能无法访问它。理想情况下,我想直接获取对转换器对象的引用RestAdpater。
public GsonConverter(Gson gson)
和公共GsonConverter(Gson gson,String charset)答案 0 :(得分:8)
以下是实现改造中发现的StringConverter
的{{1}}类的示例。基本上你必须覆盖Converter
并告诉它你想要什么。
fromBody()
将此应用于您的请求,您必须执行以下操作:
public class StringConverter implements Converter {
/*
* In default cases Retrofit calls on GSON which expects a JSON which gives
* us the following error, com.google.gson.JsonSyntaxException:
* java.lang.IllegalStateException: Expected BEGIN_OBJECT but was
* BEGIN_ARRAY at line x column x
*/
@Override
public Object fromBody(TypedInput typedInput, Type type)
throws ConversionException {
String text = null;
try {
text = fromStream(typedInput.in());
} catch (IOException e) {
e.printStackTrace();
}
return text;
}
@Override
public TypedOutput toBody(Object o) {
return null;
}
// Custom method to convert stream from request to string
public static String fromStream(InputStream in) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder out = new StringBuilder();
String newLine = System.getProperty("line.separator");
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
out.append(newLine);
}
return out.toString();
}
}