Retrofit2 and Gson not have response in logcat - android

I try to get json from Retrofit2 (Retrofit 2.1.0) and Gson. But response body is not have. No in on onFailure. Pls help me.

add this in your gradle
compile 'com.squareup.okhttp3:logging-interceptor:3.2.0'
Retrofit
HttpLoggingInterceptor logger = new HttpLoggingInterceptor();
logger.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(logger)
.build();
retrofit = new Retrofit.Builder()
.baseUrl(RETROFIT_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();

Related

Retrofit add Okhttp interceptor no use

I found something strange when I add interceptor like this:
public ApiDefinition getService() {
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(chain -> {
System.out.println("into interceptor");
Request request = chain.request();
return chain.proceed(request);
})
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(UrlConfig.BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(client)
.build();
return retrofit.create(ApiDefinition.class);
}
Then when I do call a network, nothing print just like the interceptor did't work.
Observable observable = apiDefinition.getResponse();
observable.subscribe(....)
I am confused, was there anything wrong?
apiDefinition.getResponse(); you forgetting to subscribe api call. Just getting observable, but not observing it.
apiDefinition
.getResponse()
.subscribe(.......);
if you want to intercept Network request call and print them in logcat
you can do so by adding an HttpLoggingInterceptor like that:
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
// set your desired log level
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(logging)
.build();
Sorry guys, i make some mistakes when i user dagger2 to inject ApiDefinition, so this is solved.

Retrofit2+Kotlin how to see a raw json while get response as data class

There is a service file:
interface DevbyteService {
#GET("devbytes.json")
fun getPlaylist(): Deferred<NetworkVideoContainer>
}
private val moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
object Network {
// Configure retrofit to parse JSON and use coroutines
private val retrofit = Retrofit.Builder()
.baseUrl("https://devbytes.udacity.com/")
.addConverterFactory(MoshiConverterFactory.create(moshi))
.addCallAdapterFactory(CoroutineCallAdapterFactory())
.build()
val devbytes = retrofit.create(DevbyteService::class.java)
}
So, I get a list of NetworkVideoContainer. This works fine but I want to see also a raw json answer, for example in logs.
How to do it?
With Retrofit you should use HttpLoggingInterceptor
Add the dependency in your build.gradle file as below
implementation("com.squareup.okhttp3:logging-interceptor:4.4.0")
And then set a HttpLoggingInterceptor to the Retrofit object as below
private val retrofit = Retrofit.Builder()
.baseUrl("https://devbytes.udacity.com/")
.addConverterFactory(MoshiConverterFactory.create(moshi))
.addCallAdapterFactory(CoroutineCallAdapterFactory())
.client(okHttpClient)
.build()
private val okHttpClient = OkHttpClient.Builder().addInterceptor(
HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.BODY
}
).build()
In case of deprecation warnings, simply change setLevel to:
level = HttpLoggingInterceptor.Level.BODY
The above solution gives you logcat messages very similar to the old ones set by
level = RestAdapter.LogLevel.FULL
In Retrofit 2 you should use HttpLoggingInterceptor.
Add dependency to build.gradle :
implementation 'com.squareup.okhttp3:logging-interceptor:4.4.0'
Create a Retrofit object:
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("YOUR_URL")
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
retrofit.create(ApiClient.class);

Android Retrofit - How to implement my url?

Using android retrofit, I'm having problems referring to my url.
Either of these are ok to use:
http://www.example.com/foo.asmx/dostuf
Or
http://www.example.com/foo.ashx?r=dostuff
The examples I've seen indicate:
http://www.example.com/post
What file is that processing?
So, how to I implement my url?
Thanks
private static Retrofit retrofit = null;
public static Retrofit getClient() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
retrofit = new Retrofit.Builder()
.baseUrl("Your Url")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
return retrofit;
}
I've got it.
Here it is to help out others...
The BASE url goes here:
Retrofit retrofit = new Retrofit.Builder().baseUrl("http://www.example.com/").build();
The ENDPOINT url goes here:
public interface retrofit_post1 {
#POST("example.ashx?r=dostuff")
Call<ResponseBody> update(#Body RequestBody requestBody);
}

java.io.IOException when using Retrofit with rxandroid

I need to make HTTP DELETE request to my server with body provided.
I build the retrofit object in the following way:
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.retryOnConnectionFailure(true)
.connectTimeout(2, TimeUnit.MINUTES)
.readTimeout(5, TimeUnit.MINUTES)
.writeTimeout(5, TimeUnit.MINUTES)
.build();
Gson gson = new GsonBuilder()
.registerTypeAdapter(Date.class, new GsonUTCDateAdapter())
.registerTypeAdapter(LocalDate.class, new GsonLocalDateAdapter())
.create();
return new Retrofit.Builder()
.baseUrl(AppConfig.API_BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
My Retrofit service method is:
#HTTP(method = "DELETE", path = "selfie/{publicId}/action/1", hasBody = true)
Observable<SimpleResponseModel> unlike(
#Path("publicId") String publicId,
#Body AuthorisedRequestModel model
);
I handle retrofit request/response in following way:
NetworkHelper
.getRetrofit()
.create(SelfieService.class)
.unlike(selfieModel.getPublicId(), new AuthorisedRequestModel())
.subscribeOn(Schedulers.io())
.subscribe(new CustomSubscriber<SimpleResponseModel>() {
#Override
public void onNext(SimpleResponseModel simpleResponseModel) {
ErrorHelper.handleServerError(simpleResponseModel);
}
});
I should mention, that all another requests GET,POST and PUT are working, but all DELETE requests are return me following error, from log:
HTTP FAILED: java.io.IOException: unexpected end of stream on okhttp3.Address#c6ec992c
So the request don't reach the server.
When I used Retrofit without rxandroid and made queries in AsyncTasks everything worked well.
Caused by:
Caused by: java.io.EOFException: \n not found: size=0 content=…
at okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:215)
at okhttp3.internal.http.Http1xStream.readResponse(Http1xStream.java:186)
It is an issue. You can see it on GitHub:
https://github.com/square/okhttp/issues/1517

Retrofit interceptor error

I want to add facebook access token into retrofit (2 beta 3) request, but the access token does not added.
I can add interceptor to retrofit 1.9 successfully but in retrofit 2 it has error, Is there any solution?
protected Retrofit getRestAdapter() {
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(
new Interceptor() {
#Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
String sessionId = getSessionId(); // get access token
// Request customization: add request headers
Request.Builder requestBuilder = original.newBuilder()
.header("Cookie", sessionId)
.method(original.method(), original.body());
Request request = requestBuilder.build();
return chain.proceed(request);
}
})
.build();
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl("http://tbkha.com/api/")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
}
return retrofit;
}
In retrofit retrofit 2.0 you add intercepter like this:
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(logging).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseURL)
.client(client)
.build();
Check this link for details https://futurestud.io/blog/retrofit-2-log-requests-and-responses
Similar questions:
App crash on HttpLoggingInterceptor
Retrofit2 HttpLoggingInterceptor Logcat

Categories

Resources