【问题标题】:How to pass Authorization Bearer using retrofit?如何使用改造通过授权承载?
【发布时间】:2018-02-23 13:02:56
【问题描述】:

这里我需要通过授权承载来获取服务器的响应,以防将文件上传到我正在使用改造的服务器。

我尝试了两种方式

1)

这就是我在改造接口类中初始化的方式

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

这就是我从接口类中调用它的方式

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();

任何帮助将不胜感激。 提前致谢!

【问题讨论】:

  • 你遇到了什么问题?
  • 我从服务器收到响应,但出现 403 错误
  • 这是我得到的响应,它仅在未通过授权承载令牌或错误时出现。以下是我的回复 {"timestamp":1519390221702,"status":403,"error":"Forbidden","message":"Access Denied","path":"/paychec/document/kycDocument/user/3" }
  • 你能给我你的api和token吗?
  • 我一定会给

标签: android authorization retrofit2 bearer-token


【解决方案1】:

你的改造接口方法应该是这样的:-

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

你的调用语句是这样的:-

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 );

【讨论】:

  • 当然让我检查一下兄弟
  • 我已在私聊中回复,请查收
  • 是的,它应该工作不知道第二种方式对我有用
【解决方案2】:

我试过了,它对我有用,请参考下面的代码:

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

对于 API 调用,请使用以下方法:

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) {

        }
    });
}

【讨论】:

  • 当然@Vishal 我会检查并告诉你
  • 我在个人聊天中发布的代码和其余详细信息
  • 我明白了,唯一的问题是我们不应该在接口类中提供授权承载,而是按照我在问题中提到的第二种方式传递授权承载
  • 太好了,我从不使用第二种方式。
  • 第二种方法在我的情况下有效,但都是正确的。
【解决方案3】:

你只需要在Bearer之前添加空格,我试试看:

  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();

【讨论】:

    【解决方案4】:

    Kotlin 示例: 使用 AUTH HEADER 改造获取请求

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

    call enqueue 不要忘记在tokken中添加带空格的Bearer

     val tokken =  "Bearer TOKKEN_Key"
     call.enqueue(object : Callback<JsonObject> {
            override fun onResponse(call: Call<JsonObject>, response: Response<JsonObject>) {
                
            }
    
            override fun onFailure(call: Call<JsonObject>, t: Throwable) {
                
            }
    
        })
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-23
      • 1970-01-01
      • 1970-01-01
      • 2013-10-22
      • 1970-01-01
      • 1970-01-01
      • 2022-07-29
      • 1970-01-01
      相关资源
      最近更新 更多