我需要在java中使用 OkHttp3 作为HTTP客户端,并在请求中发送授权标头。
示例:
授权:持票人 eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRaswczovL2F1dGgucGF4aW11bS5djb20iLCJhdWQiOiJodHRwczovL2FwaS5wYXhpbXVtLmNvbSIsIm5iZiI6MTQ0ODQzNzkyMCwiZXhwIjoxNDQ4NDgxMTIwLCJzdWIiOiIzNzExZDk1YS03MWU1LTRjM2ItOWQ1YS03ZmY3MGI0NDgwYWMiLCJyb2xlIjoicGF4OmIyYjphcHA6dXNlciJ9.YR8Gs7RVM-q5AxtHpeOl2zYe-zKxh5u39TUeTbiZL1k
如何使用我的用户名和密码创建此令牌? 用户名:test 密码:测试
答案 0 :(得分:5)
根据文件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"));
}
}
答案 1 :(得分:3)
以上答案导致正确的路径,但需要进行一些更改。
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();
答案 2 :(得分:0)
对于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关键字后放置空格。