How to solve response code 403 from AWS in an Android project? - android

I am using retrofit to make a POST call to AWS server. It gives me the following error
Response{protocol=h2, code=403, message=, url=https://9oe8xt95sj.execute-api.ap-southeast-1.amazonaws.com/voip-dev-wa/staging/Device/registerCustomer}
My Retrofit method is as below
Retrofit retrofit;
retrofit = new Retrofit.Builder()
.baseUrl(ApiService.API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
apiService = retrofit.create(ApiService.class);
ApiService.java
String API_BASE_URL = "SOME String";
#POST("registerCustomer")
#Headers({"Content-Type: application/json", "accept: application/json"})
Call<RegisterResponse> register(#Body Register register);
How to solve this?

The problem is I did not pass the access token as the header. So it is responding forbidden error.
OkHttpClient.Builder client = new OkHttpClient.Builder();
client.addInterceptor(new Interceptor() {
#Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request.Builder ongoing = chain.request().newBuilder();
ongoing.addHeader("Content-Type", "application/json");
ongoing.addHeader("accept", "application/json");
ongoing.addHeader("Authorization", "Bearer " + AppSetting.getInstance().getSDKDataManager().getAccessToken());
return chain.proceed(ongoing.build());
}
});

Related

Retrofit is overriding the Content Type to multiformpartbody/form-data after uploading it as audio/mp3

I'm uploading a file using Retrofit to AWS S3, however the content-type is being overridden everytime I upload. I have the the CONTENT-TYPE audio/mp3 however the file on S3 is being overridden as content-type multiformpartbody/form-data. What am I doing incorrectly?
File file = new File(String.valueOf(Uri.parse(selectedImagesList.get(current_image_uploading))));
ProgressRequestBody requestFile = new ProgressRequestBody(file, "audio/mp3");
MultipartBody.Part body =
MultipartBody.Part.createFormData("audio", file.getName(), requestFile);
RetrofitInterfaces.IUploadMP3 service = RetrofitClientInstance.getRetrofitInstance()
.create(RetrofitInterfaces.IUploadMP3.class);
Call<Void> call = service.listRepos(uploadUrls.get(current_image_uploading), body);
Most likely you need to override the header when you send the request. You can either do it for each request:
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
#Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
Request request = original.newBuilder()
.header("Content-Type"," audio/mpeg") //Set the content type here
.method(original.method(), original.body())
.build();
return chain.proceed(request);
}
}
OkHttpClient client = httpClient.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
Or, if you don't want to override every request, you can do a static override for your call like so:
public interface YourService {
#Headers("Content-Type: audio/mpeg")
#GET("/your/path")
Call<List<Task>> myFunction();
}
Both examples can be found here:

Getting Some different error in retrofit

I am using retrofit 2 for a post request, But getting response:
W/Retrofit#Response:
Ʊ
�0�W9n�RĹ��C5P}�4�mm�.T�]����sǣk����հ�{�R"�&�"�j9Z*���f�ؘ��𮈦T��!wʔ6��>A\Gǚ�JGP��H[�[�|��
This response I print from:
httpClient = new OkHttpClient.Builder()
.addInterceptor(
new Interceptor() {
#Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
// Request customization: add request headers
Request.Builder requestBuilder = original.newBuilder()
.header("Authorization", token)
.header("Content-Type", "application/json")
.header("Accept", "application/json")
.method(original.method(), original.body());
Response response = chain.proceed(chain.request());
Log.w("Retrofit#Response", response.body().string());
Request request = requestBuilder.build();
return chain.proceed(request);
}
})
.addInterceptor(logging)
.build();
Header and api :
#Headers({
"Content-Type: application/json",
"Authorization: Bearer znvct0zvHcfCtVttJQs__6C_okZ7tBSsXoyoRaMrXHoxczjBLdq5smYZToHM1KXd8EzIL1UkHwg8JsuqMHUgLKkWy-dk_51fyIfSXEWXS2h1EBINqvYpALqSi5p47_nm4Jlb6wBlKq_hS99oWUvlJW1tKOwtVC4dG0rrh7_M2CT74YsXAx-8tLQcnMBaWF1TRkgLYdaQ0wjcx4SV1lNaWdmRcZfR5HbszprFMxbe_MXK1tmd-JWfNCbWfasB-p1zecoWzfaKoNh7GjrdkF9Ek3Pu2CzWxr75Y6bC3xwgRf1zsHPJ3J_IuA5wQZVbxIz38oc23gT1bqojMP7krs-9Z5xazjAV1Qcwjj85jN2cHPFEr2NG6pGqX5_0cP7vK8RDKJAlyVyCcvclrSjFo5rkrpNsp3R1x2N_4u36ODYrm-6FNJ9P85mwIc7yvn_RSa-ggDVfmNFhhxOJIhu3B5StBT42P_xMBiw2J6yeGdJVJgqygJfrqQkgRU5IzS-u-8x6b7C48_h6703ijkmTtR77yXhwH1IDEi2BsW1egDdPsuH3LRlO9uLeBEsiRVC7jvSkuqcv7xxoEYNpRxhmPr7Eyp4Eqb0qYRcRmuFEBISG8Aj7wIf0pr2V-stpRV4BKaUhHqT7qtyDsbpmJUimuPvrmM93T22PRD3hqe8bgMYjgvVZB3BiCTlmv1pJs4qrqxNnnaVg0HpkNGC9gWKvkryCA",
})
#POST("/AppIntegraion/api/InsertSignUp")
Call<String> getUser(#Body abd params);
This issue is only occur when add Authorization header for other api this is working.
This api is working fine on postman. So this is not a server issue. Please help me.

Retrofit returns HTTP 401 for call running in background

I have a strange problem with one of my retrofit call,it works fine when the app is in the background(recent list)
I have a call through which i update my widget data,the problem is when the app is cleared of from the recent list,the call gives HTTP 401 unauthorized response.
however i pass the same bearer token with it.
please have a look at the code and suggest some help
public static OkHttpClient getOkhttpClient() {
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request newRequest = chain.request().newBuilder()
.addHeader("Authorization", "Bearer " + TokenGenerator.getToken())
.build();
return chain.proceed(newRequest);
}
}).build();
return client;
}
public static Retrofit getClient() {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(getOkhttpClient())
.addConverterFactory(JacksonConverterFactory.create())
.build();
}
return retrofit;
}

How to use Authorization Token token=A-123456789qwertyuio12 Header in Retrofit 2.0

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.

Android Retrofit 2.0.0-beta2 Post string body dynamic headers

Retrofit 2.0.0-beta2
#Headers({
"Authorization: {authorization}",
"Content-Type: application/json"
})
#POST("/api/{id}/action/")
Call<String> postfn(#Header("Authorization") String authorization, #Path("id") String id, #Body String body);
i am using Gson converter
.addConverterFactory(GsonConverterFactory.create(gson))
i am getting error code=400, message=Bad Request Should i use a custom
converter?
Please help
You can't put this two things together.
There are two ways to put dynamic headers on requests with retrofit 2.0
1: put it only in method signature
#Headers({
"Content-Type: application/json"
})
#POST("/api/{id}/action/")
Call<String> postfn(#Header("Authorization") String authorization, #Path("id") String id, #Body String body);
2: using request interceptor to add fixed dynamic headers
public class TraktvApiProvider implements Provider<TraktvApi> {
public static final String BASE_URL = "https://api-v2launch.trakt.tv/";
#Override
public TraktvApi get() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(JacksonConverterFactory.create())
.build();
retrofit.client().interceptors().add(new LoggingInterceptor());
return retrofit.create(TraktvApi.class);
}
private class LoggingInterceptor implements Interceptor {
#Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
request = request.newBuilder()
.addHeader("trakt-api-version", "2")
.addHeader("trakt-api-key", "[YOUR-API-KEY]")
.build();
Response response = chain.proceed(request);
String bodyString = response.body().string();
Log.d("Retrofit", "---------------------------------- REQUEST ----------------------------------");
Log.d("Retrofit", String.format("%s - %s", request.method(), request.url()));
Log.d("Retrofit", request.headers().toString());
Log.d("Retrofit", "---------------------------------- REQUEST ----------------------------------");
Log.d("Retrofit", "---------------------------------- RESPONSE ----------------------------------");
Log.d("Retrofit", response.headers().toString());
Log.d("Retrofit", "Body: " + bodyString);
Log.d("Retrofit", "---------------------------------- RESPONSE ----------------------------------");
return response.newBuilder()
.body(ResponseBody.create(response.body().contentType(), bodyString))
.build();
}
}
}
I moved back to the stable version 1.9 and intercepting worked fine.

Categories

Resources