Obtener respuesta HTTP sin procesar con Retrofit
Quiero obtener la respuesta http sin procesar de mi API REST. He intentado con esta interfaz:
@POST("/login")
@FormUrlEncoded
Call<retrofit.Response> login(@Field("username") String login, @Field("password") String pass,
@Field("appName") String appName, @Field("appKey") String appKey);
Pero consigo:
Java.lang.IllegalArgumentException: No se puede crear un adaptador de llamada para retrofit.Llamada para el método Api.iniciar sesión
Creo Retrofit
de esta manera:
Retrofit.Builder retrofitBuilder = new Retrofit.Builder();
retrofitBuilder.addConverterFactory(JacksonConverterFactory.create());
Retrofit retrofitAdapter = retrofitBuilder.baseUrl(baseUrl).build();
return retrofitAdapter.create(apiClass);
3 answers
Para obtener acceso a la respuesta raw, use ResponseBody
desde okhttp como su tipo de llamada.
Call<ResponseBody> login(...)
En su devolución de llamada, puede verificar el código de respuesta con el método code
de la respuesta. Esto se aplica a cualquier tipo de retorno retrofit 2, porque su devolución de llamada siempre obtiene un Response
parametrizado con su tipo de retorno real. Para asíncronos {
Call<ResponseBody> myCall = myApi.login(...)
myCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Response<ResponseBody> response, Retrofit retrofit) {
// access response code with response.code()
// access string of the response with response.body().string()
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
});
Para llamadas síncronas {
Response<ResponseBody> response = myCall.execute();
System.out.println("response code" + response.code());
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-26 17:32:45
Puede obtener información sobre los encabezados, el código de respuesta, hasta el cuerpo de respuesta json sin procesar utilizando Interceptores. Puede escribir sus Interceptores personalizados, pero prefiero usar el Interceptor de registro propio de Square. Está disponible en Maven central.
compile 'com.squareup.okhttp3:logging-interceptor:3.5.0'
Aquí está cómo usarlo
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor).build();
El cuerpo del nivel de registro imprimirá encabezados a la respuesta del cuerpo. Y en su adaptación
Retrofit retrofit = new Retrofit.Builder()
.client(client)
.baseUrl("https://yourapi.com/api/")
.build();
Ahora, abre Log Cat y verás HTTP sin procesar respuesta.
Precaución!
¡No olvides eliminar los Interceptores (o cambiar el nivel de registro a NINGUNO) en producción! De lo contrario, las personas podrán ver su solicitud y respuesta en Log Cat.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-03 08:33:10
Tenía el mismo problema pero una solución diferente. Tomé la solicitud y la envié con OkHttp3Client. Así:
//raw text
Request request = call.clone().request();
OkHttpClient client = new OkHttpClient();
okhttp3.Response test = client.newCall(request).execute();
System.out.println(test.body().string());
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-10 12:57:27