Create bearer authorization header in OkHttp java

后端 未结 3 2014
温柔的废话
温柔的废话 2021-02-07 19:56

I need to use OkHttp3 in java as a HTTP client and send Authorization header in request.

example:

Authorization: Bearer eyJ0eXA

相关标签:
3条回答
  • 2021-02-07 20:48

    According to the documentation 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"));
    
         }
      }
    
    0 讨论(0)
  • 2021-02-07 20:52

    The above answer lead to correct path but need some changes.

    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();
    
    0 讨论(0)
  • 2021-02-07 20:56

    For android Okhttp Version

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

    remember to put space after Bearer keyword.

    0 讨论(0)
提交回复
热议问题