How to pass Authorization Bearer using retrofit?
Asked Answered
F

4

6

Here I need to pass Authorization Bearer to get response from server in case of uploading file to server I am using retrofit.

I tried in two ways

1)

This is how I initialized in retrofit interface class

@POST("document/kycDocument/user/3")
Call<UploadKycpojo> uploadkycdoc(@Header("Authorization")String token, @Body UploadKycRequest uploadKycRequest); 

This is how I called it from interface class

Call<UploadKycpojo> request = RestClient.getInstance(UploadIdActivtiy.this).get().uploadkycdoc("Bearer "+auth,uploadKycRequest);

2)

OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
      @Override
      public Response intercept(Chain chain) throws IOException {
        Request newRequest  = chain.request().newBuilder()
            .addHeader("Authorization", "Bearer " + token)
            .build();
        return chain.proceed(newRequest);
      }
    }).build();

Retrofit retrofit = new Retrofit.Builder()
    .client(client)
    .baseUrl(/** your url **/)
    .addConverterFactory(GsonConverterFactory.create())
    .build();

Any help will be appreciated. Thanks in Advance!

Fulfil answered 23/2, 2018 at 13:2 Comment(16)
what problem are you facing?Hamiltonian
I m getting response from server but 403 errorFulfil
this is response I m getting and it comes only when authorization bearer token is not passed or when it is wrong. below is my response {"timestamp":1519390221702,"status":403,"error":"Forbidden","message":"Access Denied","path":"/paychec/document/kycDocument/user/3"}Fulfil
can you give me your api and token ?Hamiltonian
sure I will giveFulfil
buddy can you send me personal chat linkFulfil
is the response correct in POSTMAN?Dubose
@SantanuSur yes correctFulfil
check your body then.. are the model variables are same name as the json.. are you sure all of them are ok?Dubose
give a / before the URL in postDubose
cause for sending header both approaches are fine..]Dubose
@SantanuSur yes I have checked the body as wellFulfil
can you upload the POSTMAN screenshot?Dubose
ok do one thing..Dubose
call for a ResponseBody object instead of UploadKycpojo .. then parse the json by hand...Dubose
Let us continue this discussion in chat.Fulfil
D
4

Your retrofit interface method should be like this:-

@Multipart
@POST("document/kycDocument/user/3")
Call<UploadKycpojo> uploadkycdoc(@Header("Authorization")String token, @Part 
                                                   MultipartBody.Part file);

And your calling statement would be like this:-

File file = new File(yourStringPath);

RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), getRealPathFromURI(data.getData()));

MultipartBody.Part multipartBody =MultipartBody.Part.createFormData("file",file.getName(),requestFile);

Call<UploadKycpojo> request = RestClient.getInstance(UploadIdActivtiy.this).get()
                                            .uploadkycdoc("Bearer "+auth,multipartBody );
Dubose answered 23/2, 2018 at 13:51 Comment(3)
Sure let me check broFulfil
I have replied in personal chat please checkFulfil
ya it should work don't know the second way worked for meFulfil
F
4

You just need to add space before Bearer it's work for me try it:

  OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor()           {
  @Override
  public Response intercept(Chain chain) throws IOException {
    Request newRequest  = chain.request().newBuilder()
        .addHeader("Authorization", " Bearer " + token)
        .build();
    return chain.proceed(newRequest);
  }
}).build();

 Retrofit retrofit = new Retrofit.Builder()
.client(client)
.baseUrl(/** your url **/)
.addConverterFactory(GsonConverterFactory.create())
.build();
Faubourg answered 2/9, 2019 at 16:18 Comment(0)
H
3

I did try and it's working for me please refer below code:

@Multipart
@POST("document/kycDocument/user/3")
Call<UploadKycpojo> uploadkycdoc(@Header("Authorization")String token, @Part 
MultipartBody.Part file, @PartMap() Map<String,
        RequestBody> partMap);

And for API call use below method:

private void uploadkycdoc() {
MultipartBody.Part filePart;
    HashMap<String, RequestBody> requestBodyMap = new HashMap<>();
    requestBodyMap.put("imageSlide", RequestBody.create(MediaType.parse("multipart/form-data"), "front"));

    ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);
    Call<UploadKycpojo> uploadkycdocCall = null;

    File file = new File(getRealPathFromURI(fileUri, context));
    RequestBody requestFile = RequestBody.create(MediaType.parse("*/*"), file);
    filePart= MultipartBody.Part.createFormData("file", file.getName(),
            requestFile);

    uploadkycdocCall = apiInterface.uploadkycdoc("Bearer " + token, filePart, requestBodyMap);

    uploadkycdocCall.enqueue(new Callback<UploadKycpojo>() {
        @Override
        public void onResponse(Call<UploadKycpojo> call, Response<UploadKycpojo> response) {
            cancelProgressDialog();
            try {
                if (response.isSuccessful()) {

                } else {

                }
            } catch (Exception e) {

            }
        }

        @Override
        public void onFailure(Call<UploadKycpojo> call, Throwable t) {

        }
    });
}
Hamiltonian answered 23/2, 2018 at 13:49 Comment(6)
Sure @Vishal I will check and let you knowFulfil
the code and remaining details I have posted on personal chatFulfil
I got it, only the thing is Authorization bearer we should not give in interface class instead I have followed the second way to pass Authorization bearer which I mentioned in my questionFulfil
great I never use second way.Hamiltonian
second method worked in my case, but both are correct.Fulfil
You can accept my answer if it's useful to you so it's also useful to other user.Hamiltonian
V
0

Kotlin Ex: retrofit Get request with AUTH HEADER

@GET("api-shipping/Apps")
fun getApp(@Header("Authorization") auth: String) : retrofit2.Call<JsonObject>

Call enqueue don't forget to add Bearer with a space in token

 val token =  "Bearer TOKEN_Key"
 call.enqueue(object : Callback<JsonObject> {
        override fun onResponse(call: Call<JsonObject>, response: Response<JsonObject>) {
        }

        override fun onFailure(call: Call<JsonObject>, t: Throwable) {
        }
    })
}
Vitriol answered 30/12, 2021 at 7:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.