Create bearer authorization header in OkHttp java

眉间皱痕 提交于 2019-12-08 19:39:50

问题


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

example:

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

how can I create this token using my username and password? username: test password: test


回答1:


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

     }
  }



回答2:


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();



回答3:


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.



来源:https://stackoverflow.com/questions/49463607/create-bearer-authorization-header-in-okhttp-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!