【问题标题】:Retrofit Bearer token改造不记名令牌
【发布时间】:2018-08-24 02:10:55
【问题描述】:

我尝试通过 POST json {"email":"test@example.com","password":"test"} 接收令牌。在邮递员中它可以工作: Postman request。 我尝试在 Android Studio 中做同样的事情。 我创建类 Token:

   public class Token {
    @SerializedName("token")
    @Expose
    public String token;
   }

还有类APIclient

    class APIClient {

    private static Retrofit retrofit = null;

    static Retrofit getClient() {

        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

        retrofit = new Retrofit.Builder()
                .baseUrl("http://mybaseurl.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();

        return retrofit;
    }

}

和接口APIInterface:

    interface APIInterface {
    @POST("/authenticate")
    Call<Token> getLoginResponse(@Body AuthenticationRequest request);
}

和类 AuthenticationRequest:

    public class AuthenticationRequest {
    String email;
    String password;
}

在MainActivity的onCreate中:

  apiInterface = APIClient.getClient().create(APIInterface.class);
  authenticationRequest.email="test@example.com";
  authenticationRequest.password="test";
  getTokenResponse();

这是我的 getTokenResponse 方法:

    private void getTokenResponse() {
    Call<Token> call2 = apiInterface.getLoginResponse(authenticationRequest);
    call2.enqueue(new Callback<Token>() {
        @Override
        public void onResponse(Call<Token> call, Response<Token> response) {
            Token token = response.body();
        }
        @Override
        public void onFailure(Call<Token> call, Throwable t) {
            call.cancel();
        }
    });
}

这就是我在 Logcat 中看到的:

    03-15 10:53:56.579 20734-20756/com.retrofi2test D/OkHttp: --> POST http://mybaseurl.com/authenticate http/1.1
03-15 10:53:56.579 20734-20756/com.retrofi2test D/OkHttp: Content-Type: application/json; charset=UTF-8
03-15 10:53:56.579 20734-20756/com.retrofi2test D/OkHttp: Content-Length: 46
03-15 10:53:56.579 20734-20756/com.retrofi2test D/OkHttp: {"email":"test@example.com","password":"test"}
03-15 10:53:56.579 20734-20756/com.retrofi2test D/OkHttp: --> END POST (46-byte body)

你能告诉我我做错了什么吗?每次我想通过 GET 方法从服务器获取信息时,我都需要提供令牌。 如何在 Android 代码中接收和保存令牌?

【问题讨论】:

  • 您是否从标头获取/发送令牌?
  • 在 GET 方法中我在标头授权中发送令牌
  • 我已经发布了答案。请看一下。

标签: android post retrofit2 restful-authentication


【解决方案1】:

试试这个

 interface APIInterface {
  @POST("/authenticate")
  Call<Token> getLoginResponse(@Header("Authorization") String token, @Body AuthenticationRequest request);
 }

tokenBearer token

【讨论】:

    【解决方案2】:

    你应该在标题中添加application/json

    interface APIInterface {
    @Headers({"Content-Type: application/json", "Accept: application/json"})
    @POST("/authenticate")
    Call<Token> getLoginResponse(@Body AuthenticationRequest request);
    }
    

    【讨论】:

      【解决方案3】:

      要从您那里获取访​​问令牌,您需要从响应中获取标头并从标头中读取值。

      Callback<User> user = new Callback<User>() {
          @Override
          public void success(User user, Response response) {
              List<Header> headerList = response.getHeaders();
              //iterating list of header and printing key/value. 
              for(Header header : headerList) {
                  Log.d(TAG, header.getName() + " " + header.getValue());
              }
          }
      }
      

      从标头(即AccessToken)获得所需的值后,您可以将该值存储在存储中。例如SharedPreference

      因此,下次当您需要该值时,您可以直接从 Storage 中获取该值。例如SharedPreference

      现在,当您通过 GETPOST 或任何其他方法的任何 Web 服务请求时。您必须将其传递给标头请求。

      @GET("/tasks")
      Call<List<Task>> getTasks(@Header("Content-Range") String contentRange);
      

      或者如果你每次都需要传递它,你可以直接从你的Retrofit类传递。

      Request request = original.newBuilder()
              .header("User-Agent", "Your-App-Name")
              .header("Accept", "application/vnd.yourapi.v1.full+json")
              .method(original.method(), original.body())
              .build();
      

      【讨论】:

        猜你喜欢
        • 2021-09-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-10
        • 1970-01-01
        • 2022-08-15
        • 2017-04-23
        • 2017-10-27
        相关资源
        最近更新 更多