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
Related
I am using some url for my apis which redirect to other one but i have some problem about POST methods ..
It gives me this message in the log:
405 Method Not Allowed
I am using retrofit in my app ..
How can i fix it to accept POST methods also?
This is my code:
public static Retrofit getClient() {
pref = getContext().getSharedPreferences(getContext().getPackageName(), 0);
languageSetting = pref.getString("languageSetting", null);
if (retrofit == null) {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder()
.connectTimeout(5, TimeUnit.MINUTES)
.readTimeout(5, TimeUnit.MINUTES);
httpClient.addInterceptor(logging);
// httpClient.followRedirects(false);
httpClient.addInterceptor(chain -> {
Request original = chain.request();
Request request = original.newBuilder()
.header("Content-Type", "application/x-www-form-urlencoded")
.header("Accept", "application/json")
.header("Lang", languageSetting != null ? languageSetting : "EN")
.header("TokenKey", Constants.TOKEN)
.method(original.method(), original.body())
.build();
return chain.proceed(request);
}
);
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(httpClient.build())
.build();
}
return retrofit;
}
I have tried it on post man and same issue but when i activate this option, it works fine :
The question now how to activate Follow Original HTTP method in android & Retrofit?
Sometimes I am getting error “unexpected end of stream on connection” while calling web service from android using go daddy server and hosting.
In pick hours my application got this error.
AppController.class
private void initRetrofitConfig() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(BuildConfig.DEBUG ? HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.NONE);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request().newBuilder().addHeader("Connection", "close").build();
return chain.proceed(request);
}
})
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(1, TimeUnit.MINUTES)
.writeTimeout(5, TimeUnit.MINUTES)
.retryOnConnectionFailure(true)
.build();
Retrofit retrofit = new Retrofit.Builder()
.client(client)
.baseUrl(SERVICE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
.build();
apiEndpoint = retrofit.create(ApiEndpoint.class);
}
public ApiEndpoint getApiEndpoint() {
if (apiEndpoint == null) {
initRetrofitConfig();
}
return apiEndpoint;
}
I'm trying to implement auth via x-www-form-urlencoded with Retrofit 2 on Android but faced a problem, that Header Content-Type not set with #FormUrlEncoded annotation, as well as I'm trying to set it manually, but when I'm setting it with a typo like Cotent-Type it works correctly and I can see it in headers.
Retrofit version: 2.4.0
So my question: why #FormUrlEncoded not set a content type as well as #Header annotation or what can remove it from headers.
My request:
#FormUrlEncoded
#POST("account/login")
Single<LoginResponse> login(#Field("memberId") String memberId,
#Field("pin") String pin);
OkHTTP/Retrofit provider with interceptors:
#Singleton
#Provides
Retrofit provideRetrofit(final OkHttpClient client, final Moshi moshi) {
return new Retrofit.Builder()
.baseUrl(Configuration.BASE_URL)
.client(client)
.addConverterFactory(MoshiConverterFactory.create(moshi))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
}
#Provides
OkHttpClient provideOkHttpClient(#AppContext final Context context) {
final OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
.readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
.followRedirects(true)
.followSslRedirects(true)
.addInterceptor(createLanguageInterceptor(context));
if (BuildConfig.DEBUG) {
builder.addInterceptor(new LoggingInterceptor());
}
return builder.build();
}
Interceptor createLanguageInterceptor(#AppContext final Context context) {
Locale current = context.getResources().getConfiguration().locale;
return chain -> {
Request.Builder builder = chain.request().newBuilder();
builder.addHeader("Accept-Language", current.getLanguage());
Request request = builder.build();
Response response = chain.proceed(request);
return response;
};
}
As a workaround, I've implemented the following interceptor:
Interceptor createHeaderTransformationInterceptor() {
return chain -> {
final Request request = chain.request();
String dataType = request.header("Data-Type");
final Request resultRequest = dataType == null
? request
: chain.request().newBuilder()
.removeHeader("Data-Type")
.addHeader("Content-Type", dataType)
.build();
return chain.proceed(resultRequest);
};
}
and it works fine with the following annotation:
#Headers({"Data-Type: application/x-www-form-urlencoded"})
UPD: the reason that my interceptor didn't see that is in a place where the content type is stored. The right way to see that header in an interceptor:
if (requestBody.contentType() != null) {
logger.log("Content-Type: " + requestBody.contentType());
}
if (requestBody.contentLength() != -1) {
logger.log("Content-Length: " + requestBody.contentLength());
}
By this Request
#FormUrlEncoded
#POST("account/login")
Single<LoginResponse> login(#Field("memberId") String memberId,
#Field("pin") String pin);
method #POST and #FormUrlEncoded automatic add
Content-Type: application/x-www-form-urlencoded in header you can check in log by
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(interceptor.setLevel(HttpLoggingInterceptor.Level.BODY))
.connectTimeout(2, TimeUnit.MINUTES)
.writeTimeout(2, TimeUnit.MINUTES)
.readTimeout(2, TimeUnit.MINUTES)
.build();
it print all log in verbose mode
im trying to consume an api that has that authorization header, i can get a 200 response in Postman with all data but cant get it to work in retrofit
May be you need add the Token using OkHttp Interceptor.
OkHttpClient client = new OkHttpClient.Builder()
.addNetworkInterceptor(mTokenInterceptor)
.build();
then add it to Retrofit:
Retrofit retrofit = new Retrofit.Builder()
.client(client)
.baseUrl(base_url)
.build();
the mTokenInterceptor:
Interceptor mTokenInterceptor = new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (mToken != null) {
Request.Builder requestBuilder = request.newBuilder()
.addHeader("Authorization", mToken);
Request newRequest = requestBuilder.build();
return chain.proceed(newRequest);
}
return chain.proceed(request);
}
};
when you get the Token, just assign the mToken,
You can try something like below, just a crude example
#GET("your server url goes here")
Call<Your_Model_Class> getServerData(#Header("Authorization") String token);
Pass your token to getServerData method.
I need to log the response my server is sending after a call, because I am receiving a MalformedJsonException, to see what is going on.
I am using this code:
OkHttpClient client = new OkHttpClient();
client.interceptors().add(new Interceptor() {
#Override
public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
com.squareup.okhttp.Response respuesta = chain.proceed(chain.request());
Log.i("David", "Response: "+respuesta.toString());
return response;
}
});
Retrofit builder = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build()
.client(client);
I have done this following this tutorial. I get an error in ".client(client); line: "client() in Retrofit cannot be applied to (com.squareup.okhttp.OkHttpClient)
What I am doing wrong? What do I need to do to intercept the response from the server, to see what's wrong with the JSON?
Thank you.
client(OkHttpClient) is a method of Retrofit.Builder() not of Retrofit. Change
Retrofit builder = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build()
.client(client);
with
Retrofit builder = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build() ;