Create bearer authorization header in OkHttp java

后端 未结 3 942
花落未央
花落未央 2021-02-07 20:29

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:55

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

提交回复
热议问题