2015-07-18 60 views
4

我是新的改造。我向一个网站发布POST请求。网站将响应作为HTML返回。所以我会解析它。然而,Retrofit尝试将其解析为JSON。怎么办?获得Html响应与改造

@FormUrlEncoded 
@POST("/login.php?action=login") 
void postCredentials(@Field("username") String username, 
        @Field("password") String password); 

我应该使用一个回调?

回答

5

改造使用converter处理来自终端和请求的响应,以及。默认情况下,Retrofit使用GsonConverter,它使用gson库将JSON响应编码为Java对象。您可以在构建您的Retrofit实例时覆盖它以提供您自己的转换器。

您需要实现的接口是here(github.com)。这里还有一个简短的教程,虽然对于使用Jackson库来说,许多位仍然是相关的:futurestud.io/blog

还要注意,转换器可以两种方式转换请求和响应。由于您只希望在一个方向上进行HTML解析,因此您可能希望在自定义转换器中使用GsonConverter,以便将传出的Java对象转换为JSON(toBody方法)。

0

可能不是最好的解决办法,但这个我怎么设法得到一个html页面与改造来源:

MainActivity.java

ApiInterface apiService = ApiClient.getClient(context).create(ApiInterface.class); 

//Because synchrone in the main thread, i don't respect myself :p 
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
StrictMode.setThreadPolicy(policy); 

//Execution of the call 
Call<ResponseBody> call = apiService.url(); 
response = call.execute(); 

//Decode the response text/html (gzip encoded) 
ByteArrayInputStream bais = new ByteArrayInputStream(((ResponseBody)response.body()).bytes()); 
GZIPInputStream gzis = new GZIPInputStream(bais); 
InputStreamReader reader = new InputStreamReader(gzis); 
BufferedReader in = new BufferedReader(reader); 

String readed; 
while ((readed = in.readLine()) != null) { 
     System.out.println(readed); //Log the result 
} 

ApiInterface.java

@GET("/") 
Call<ResponseBody> url(); 

ApiClient.java

public static final String BASE_URL = "https://www.google.com"; 

private static Retrofit retrofit = null; 

public static Retrofit getClient(Context context) { 
    if (retrofit==null) { 

     OkHttpClient okHttpClient = new OkHttpClient().newBuilder() 
       .build(); 

     retrofit = new Retrofit.Builder() 
       .baseUrl(BASE_URL) 
       .addConverterFactory(ScalarsConverterFactory.create()) 
       .client(okHttpClient) 
       .build(); 
    } 
    return retrofit; 
}