Anil Thakur
Anil Thakur

Reputation: 123

How to get header response in Retrofit in Android?

This is my end point :

@POST("v4/MyStore/data")
Observable<Headers> requestStore(@Body MyStoreRequest request);

I am trying to get response like this :

requestService.requestStore(request)
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.computation())
                .map(headers -> {
                   Log.d("Response",""+headers);
                    return headers;
                }).subscribe(headers -> {
                            Log.d("Response",""+headers);
                        },
                        error -> {
                           Log.d("ERRRROOOR","Error");
                        });

I am getting error like below:

Exception: retrofit2.adapter.rxjava.HttpException: HTTP 403 Forbidden

While in postman I am getting response:

Connection →keep-alive
Content-Length →0
Content-Type →application/json; charset=utf-8
Date →Mon, 03 Sep 2018 18:47:30 GMT
MYid →f028df50-c8c5-4cce-92e7-70130345ba46

What I am doing wrong here?

Upvotes: 5

Views: 4967

Answers (2)

Rajat Beck
Rajat Beck

Reputation: 1633

You have to use a Response as your response model because your api is entering error stream in with a code 403

 @POST("v4/MyStore/data")
 Observable<Response<Void>> requestStore(@Body MyStoreRequest request);

now when you consume response

 requestService.requestStore(request)
            .subscribeOn(Schedulers.io())
            .observeOn(Schedulers.computation())
            .map(response -> {
               Log.d("Response",""+response);
                return response.header();
            }).subscribe(headers -> {
                        Log.d("Response",""+headers);
                    },
                    error -> {
                       Log.d("ERRRROOOR","Error");
                    });

response.header() will return you the header you want even when your api fails

Upvotes: 2

Shashanth
Shashanth

Reputation: 5180

Probably you're missing headers in your API request from Android client. As per your comment, you're sending bearer token in Authorization headers.

So, you need to send bearer token along with request body like below

@Headers({
        "Authorization: Bearer <your_bearer_token_here>", /* change token here */
        "Content-Type: application/json"
})
@POST("v4/MyStore/data")
Observable<Headers> requestStore(@Body MyStoreRequest request);

Example,

@Headers({
        "Authorization: Bearer ca0df98d-978c-410b-96ec-4e592a788c18",
        "Content-Type: application/json"
})
@POST("v4/MyStore/data")
Observable<Headers> requestStore(@Body MyStoreRequest request);

Upvotes: 0

Related Questions