Create bearer authorization header in OkHttp java

后端 未结 3 944
花落未央
花落未央 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:39

    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.

提交回复
热议问题