在 OkHttp java 中创建承载授权 header

Create bearer authorization header in OkHttp java

我需要在 java 中使用 OkHttp3 作为 HTTP 客户端并在请求中发送授权 header。

示例:

Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRaswczovL2F1dGgucGF4aW11bS5djb20iLCJhdWQiOiJodHRwczovL2FwaS5wYXhpbXVtLmNvbSIsIm5iZiI6MTQ0ODQzNzkyMCwiZXhwIjoxNDQ4NDgxMTIwLCJzdWIiOiIzNzExZDk1YS03MWU1LTRjM2ItOWQ1YS03ZmY3MGI0NDgwYWMiLCJyb2xlIjoicGF4OmIyYjphcHA6dXNlciJ9.YR8Gs7RVM-q5AxtHpeOl2zYe-zKxh5u39TUeTbiZL1k

如何使用我的用户名和密码创建此令牌? 用户名:测试 密码:测试

根据文档here

  private final OkHttpClient client = new OkHttpClient();
  private final String url = "http://test.com";

  public void run(String token) throws Exception {
    Request request = new Request.Builder()
    .url(url)
    //This adds the token to the header.
    .addHeader("Authorization", "Bearer " + token)
    .build();
     try (Response response = client.newCall(request).execute()) {
          if (!response.isSuccessful()){
             throw new IOException("Unexpected code " + response);
          }

         System.out.println("Server: " + response.header("anykey"));

     }
  }

以上答案指向正确的路径,但需要进行一些更改。

private  Response requestBuilderWithBearerToken(String userToken) throws IOException {
           OkHttpClient client = new OkHttpClient();
           Request request = new Request.Builder()
                   .url(YourURL)
                   .get()
                   .addHeader("cache-control", "no-cache")
                   .addHeader("Authorization" , "Bearer " + userToken)
                   .build();

           return  client.newCall(request).execute();

对于android Okhttp版本

public Call post(String url, String json, Callback callback, String token) {
    OkHttpClient client = new OkHttpClient();

    RequestBody body = RequestBody.create(JSON, json);
    Request request = new Request.Builder()
        .url(url)
        .addHeader("Authorization", "Bearer " + token)
        .post(body)
        .build();
    Call call = client.newCall(request);
        call.enqueue(callback);
    return call;
}

记得在 Bearer 关键字后加上 space。