【问题标题】:Retrofit request Header with params带参数的改造请求标头
【发布时间】:2018-02-01 19:27:49
【问题描述】:

我想在 Android 应用程序中使用两个标头发出请求,第一个标头有一个参数。我试过这个:

  @Headers("Content-Type: application/json")
@GET("/ebuzon/client/show")
Call<Client> showClient(@Header("Authorization") String token);

 call = api.showClient(" Bearer " +MySharedUser.getInstance().getToken());

401 未经授权

已编辑:这应该可行,请参阅@Robert 答案。我的问题也是更新令牌

 @GET("/ebuzon/client/show")
Call<Client> showClient(@Header("Authorization") String token,
                        @Header("Content-Type") String appJson);

 call = api.showClient(" Bearer" +MySharedUser.getInstance().getToken(), "application/json");

401 未经授权

@Headers({"Authorization: Bearer {token}","Content-Type: application/json"})
@GET("/ebuzon/client/show")
Call<Client> showClient(@Path("token") String token);

IllegalArgumentException:URL“/ebuzon/client/show”不包含“{token}”。 (参数#1)

我在这样的角度上做同样的事情,它正在工作

var obj = this.http.get("/ebuzon/client/show",
     {headers: new HttpHeaders().set("Authorization", " Bearer "+ this.token).append("Content-Type","application/json")})
        .map(res => {
            console.log(res);
            return res
        })
        .catch(err => {
            console.log(err);
            return err;
        })
    return obj;

感谢您的帮助。

【问题讨论】:

标签: android retrofit2


【解决方案1】:

也许这会对您有所帮助..也许您需要在请求中添加标头..

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

【讨论】:

  • 两个答案都很好,因为我在更新令牌时遇到了另一个问题,谢谢!!
【解决方案2】:

方法 1 或 2 应该可以。

我相信问题可能出在你构建价值的方式上。

(" Bearer" +MySharedUser.getInstance().getToken());

这将导致类似

" Bearer{SOME_TOKEN}" 

在现实中,您很可能希望它像

"Bearer {SOME_TOKEN}"

【讨论】:

  • 我都试过了,我得到了相同的结果 401 call = api.showClient(" Bearer " + MySharedUser.getInstance().getToken());
  • 你确定你在 MySharedUser.getInstance().getToken() 上有一个值吗?
  • 我没有以正确的方式更新令牌,你是对的。非常感谢。
猜你喜欢
  • 1970-01-01
  • 2018-12-09
  • 2014-01-22
  • 2016-02-06
  • 2015-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-18
相关资源
最近更新 更多