改装请求带有参数的标题

时间:2018-02-01 09:53:53

标签: android retrofit2

我想在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 UNATHORIZED

编辑:这应该有效,请参阅@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 UNATHORIZED

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

IllegalArgumentException:URL&#34; / ebuzon / client / show&#34;不包含&#34; {token}&#34;。 (参数#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;

感谢您的帮助。

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分:1)

方法1或2应该有效。

我认为问题可能在于你构建价值的方式。

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

这会产生类似

的内容
" Bearer{SOME_TOKEN}" 

实际上,你很可能希望它像

"Bearer {SOME_TOKEN}"
相关问题