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.
Related
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());
}
});
I have query parameters that is used for all requests. It is added to the base url as follow
private val baseUrl = HttpUrl.Builder()
.scheme("http")
.host("ws.audioscrobbler.com")
.addPathSegment("2.0")
.addPathSegment("")
.addQueryParameter("format", "json")
.addQueryParameter("api_key", "val")
.build()
retrofit = Retrofit.Builder()
.baseUrl(baseUrl)
.client(okHttpClient)
.build()
The api service call is
#GET("./")
fun searchTracks(#Query("otherParam") query: String): Call<Any>
The url is built correctly till the actual call is made. It removes the query params added in the base url and keeps only the one added in service call.
Shown in debugging till the delegate.enqueue() is called in ExecutorCallAdapterFactory:"http://ws.audioscrobbler.com/2.0/?format=json&api_key=val&otherParam=val"
shown in logs (via interceptor): "http://ws.audioscrobbler.com/2.0/?otherParam=val"
Any idea why this happens and how to keep the parameters?
You should add query parameters to url in request interceptor.
OkHttpClient.Builder httpClient =
new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
HttpUrl originalHttpUrl = original.url();
HttpUrl url = originalHttpUrl.newBuilder()
.addQueryParameter("format", "json")
.addQueryParameter("api_key", "val")
.build();
// Request customization: add request headers
Request.Builder requestBuilder = original.newBuilder()
.url(url);
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
I have specific document, which requires GET method type and also pass a JSON body
For example
curl -H "Content-Type: application/json" -X GET -d '{"Date":"10-10-2017"}'
https://apibaseurl.com:8081/apibaseurl/methodname
Its working fine in insomnia rest client. I have also written code for same. Please suggest if any way to get proper response
HttpResponse<String> response = Unirest.get("url")
.header("cookie", "PHPSESSID=7aikas61q77eskm3k1sfon5bq7")
.header("Authorization", "Basic authantication=")
.header("content-type", "application/json")
.body("{\"Date\":\"10-10-2017\"}")
.asString();
I have also write code using okhttp but not working.
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\"Date\":\"10-10-2017\"}");
Request request = new Request.Builder()
.url("url")
.get()
.addHeader("cookie", "PHPSESSID=7aikas61q77eskm3k1sfon5bq7")
.addHeader("authorization", "Basic YXBpcHVidXNlcjpzX20kVDJdXVNNbTY=")
.addHeader("content-type", "application/json")
.build();
Response response = client.newCall(request).execute();
Now i need to get thing shadow from aws-iot api.so when i hit same request into postman got 200ok in response.
From the app-side i got 403 i.e.forbidden.
Here i used "okhttp client" for fetch the request.
also attached image where i got 200ok response.
Now what i do from app side?I think its permission issue but not able to resolved please suggest.
also attached code as follows:-
Interceptor interceptor = new Interceptor() {
#Override
public okhttp3.Response intercept(Interceptor.Chain chain) throws IOException {
Request newRequest = chain.request()
.newBuilder()
.addHeader("content-type", "application/x-www-form-urlencoded")
.addHeader("host", "ag7fce49bf5ti.iot.us-east-1.amazonaws.com")
.addHeader("x-amz-date", "20160919T054450Z")
.addHeader("authorization", "AWS4-HMAC-SHA256 Credential=AKIAJ6XB3CLURFLV6ISQ/20160919/us-east-1/iotdata/aws4_request, SignedHeaders=content-type;host;x-amz-date, Signature=af7cd8cee7dd4763cff3a1c8f91cdde1fa22cc68012248a694cee098981bc623")
.build();
return chain.proceed(newRequest);
}
};
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.interceptors().add(interceptor);
client = builder.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://ag7fce49bf5ti.iot.us-east-1.amazonaws.com/things/dm_project/shadow/")
//.addConverterFactory(client)
.client(client)
.build();
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.