gpt4 book ai didi

java - 是否可以使用普通 Java 使用 okHttp 客户端执行 OAuth2 请求

转载 作者:行者123 更新时间:2023-12-05 03:28:54 33 4
gpt4 key购买 nike

我尝试将 api 与 OAuth2 结合使用。与 postman 一起工作。但现在我尝试用 Java 编写它。我没有spring boot,是一个简单的Maven项目我找到的唯一例子是这个

Example okhttp

但它似乎只适用于基本身份验证。

我的问题是,是否可以使用 okhttp 执行 Oauth2?或者是错误的库?

最佳答案

所以我的解决方案是生成post请求以获取 token

 private static void postCall() throws IOException {

// Create a new HTTP client
OkHttpClient client = new OkHttpClient()
.newBuilder()
.build();

// Create the request body
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.Companion.create("password=yourPassword&grant_type=password&client_id=yoirClientId&username=yourUserName",mediaType);

// Build the request object, with method, headers
Request request = new Request.Builder()
.url("https://your-address-to-get-the-token/openid-connect/token")
.method("POST", body)
.build();

// Perform the request, this potentially throws an IOException
Response response = client.newCall(request).execute();
// Read the body of the response into a hashmap
Map<String, Object> responseMap = new ObjectMapper().readValue(response.body().byteStream(), HashMap.class);
// Read the value of the "access_token" key from the hashmap
String accessToken = (String) responseMap.get("access_token");
//System.out.println(responseMap.toString());
// Return the access_token value
System.out.println("accessToken " + accessToken);

request = new Request.Builder()
.url("https://your-endpoint-rest-call")
.method("GET", null)
.addHeader("Authorization", "Bearer " + accessToken)
.build();

response = client.newCall(request).execute();
System.out.println("Response" + response.body().string());


}

关于java - 是否可以使用普通 Java 使用 okHttp 客户端执行 OAuth2 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71146045/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com