krialix
krialix

Reputation: 125

Get Html response with Retrofit

I'm new to Retrofit. I make a POST request to a website. Website returns response as HTML. So I will parse it. However Retrofit try to parse it as JSON. How can do it?

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

Should I use a callback?

Upvotes: 6

Views: 14349

Answers (2)

bNj06
bNj06

Reputation: 113

May be not the best solution but this how i managed to get the source of an html page with retrofit:

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;
}

Upvotes: 2

Hassan Ibraheem
Hassan Ibraheem

Reputation: 2369

Retrofit uses a converter to process responses from endpoints and requests as well. By default, Retrofit uses GsonConverter, which encoded JSON responses to Java objects using the gson library. You can override that to supply your own converter when constructing your Retrofit instance.

The interface you need to implement is available here (github.com). Here's a short tutorial as well, although for using Jackson library, many bits are still relevant: futurestud.io/blog

Also note that the converter works both ways, converting requests and responses. Since you want HTML parsing in one direction only, you may want to use GsonConverter in your custom converter, to convert outgoing Java objects to JSON, in the toBody method.

Upvotes: 5

Related Questions