【问题标题】:Is it possible to do a OAuth2 request with okHttp client with plain Java是否可以使用普通 Java 的 okHttp 客户端执行 OAuth2 请求
【发布时间】:2022-06-23 00:37:13
【问题描述】:

我尝试使用带有 OAuth2 的 api。与邮递员一起工作。 但现在我尝试用 Java 编写它。我没有spring boot,这是一个简单的Maven项目 我发现的唯一例子是这个

Example okhttp

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

我的问题是,是否可以使用 okhttp 进行 Oauth2?还是错误的库?

【问题讨论】:

    标签: java oauth-2.0 okhttp


    【解决方案1】:

    所以我的解决方案是生成发布请求以获取令牌

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

    【讨论】:

      猜你喜欢
      • 2019-04-05
      • 2019-04-20
      • 1970-01-01
      • 1970-01-01
      • 2016-06-15
      • 2016-12-27
      • 1970-01-01
      • 2016-02-27
      • 2016-06-13
      相关资源
      最近更新 更多