我需要在java中使用OkHttp3作为HTTP,并在请求中发送授权头。
示例:
授权:无记名eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRaswczovL2F1dGgucGF4aW11bS5djb20iLCJhdWQiOiJodHRwczovL2FwaS5wYXhpbXVtLmNvbSIsIm5iZiI6MTQ0ODQzNzkyMCwiZXhwIjoxNDQ4NDgxMTIwLCJzdWIiOiIzNzExZDk1YS03MWU1LTRjM2ItOWQ1YS03ZmY3MGI0NDgwYWMiLCJyb2xlIjoicGF4OmIyYjphcHA6dXNlciJ9.YR8Gs7RVM-q5AxtHpeOl2zYe-zKxh5u39TUeTbiZL1k
如何使用我的用户名和密码创建此令牌?用户名:测试密码:测试
发布于 2018-03-24 11:23:04
根据文档这里
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"));
}
}发布于 2018-11-07 16:31:45
以上的答案导致正确的路径,但需要一些改变。
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();发布于 2019-07-29 18:03:40
用于android版本
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;
}记住把空格放在比勒关键字后面。
https://stackoverflow.com/questions/49463607
复制相似问题