在异步模式下改装调用
public void success(T t, Response rawResponse)
Run Code Online (Sandbox Code Playgroud)
t是转换后的响应,rawResponse是原始响应.这使您可以访问原始响应和转换后的响应.
在同步模式下,您可以获得转换后的响应或原始响应
转换后的反应
@GET("/users/list")
List<User> userList();
Run Code Online (Sandbox Code Playgroud)
原始反应
@GET("/users/list")
Response userList();
Run Code Online (Sandbox Code Playgroud)
Response对象确实有一个获取正文的方法
TypedInput getBody()
Run Code Online (Sandbox Code Playgroud)
而改装api确实有一个转换器类,可以将其转换为java对象
Object fromBody(TypedInput body,Type type)
Run Code Online (Sandbox Code Playgroud)
但我无法弄清楚如何获取Converter对象的实例
我或许可以创建一个Converter类的实例,但这需要知道用于创建RestAdapter的Gson对象,我可能无法访问它.理想情况下,我想直接获取RestAdpater对转换器对象的引用.
public GsonConverter(Gson gson)和公共GsonConverter(Gson gson,String charset)这是一个在改造StringConverter中实现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();
}
}
Run Code Online (Sandbox Code Playgroud)
将此应用于您的请求,您必须执行以下操作:
// initializing Retrofit's rest adapter
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(ApiConstants.MAIN_URL).setLogLevel(LogLevel.FULL)
.setConverter(new StringConverter()).build();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11943 次 |
| 最近记录: |