Get Html response with retrofit

I am new to Retrofit. I am making a POST request to a website. The website returns the response as HTML. Therefore, I will analyze it. However, Retrofit will try to parse it as JSON. How can I do that?

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

Should I use a callback?

+4
source share
2 answers

As part of the refinement, it is used converterto process responses from endpoints and requests. By default, Retrofit uses GsonConverter, which encodes JSON responses to Java objects using the library gson. You can override this to provide your own converter when creating your Retrofit instance.

, , (github.com). , : futurestud.io/blog

, , . , HTML , GsonConverter Java JSON, toBody.

+5

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

Source: https://habr.com/ru/post/1598545/


All Articles