java - Java HTTP library to request an OpenAPI token and issue Authorized requests
问题描述
I need to perform a set of HTTP Operations which include a POST with Form Parameters and a GET using HTTP Headers to set the Authorization Header:
public void testResourceIsSecured() {
String authResponse = ClientBuilder.newClient()
.target("http://localhost:8080/auth/realms/thorntail-cmd-client/protocol/openid-connect/token")
.request()
.post(Entity.form(new Form()
.param("grant_type", "password")
.param("client_id", "thorntail-cmd-client-example")
.param("username", "user1")
.param("password", "password1")
), String.class);
String accessToken = getAccessTokenFromResponse(authResponse);
String serviceResponse = ClientBuilder.newClient()
.target("http://localhost:8080/mpjwt/secured")
.request()
.header(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken)
.get(String.class);
Assert.assertEquals("Hi user1, this resource is secured", serviceResponse);
}
private String getAccessTokenFromResponse(String response) {
String tokenStart = response.substring("{\"access_token\":\"".length());
return tokenStart.substring(0, tokenStart.indexOf("\""));
}
The above code works with Resteasy client API, though I'm not allowed to use this library because of the dependencies it brings in. Which Java HTTP library would you advice to use as replacement, which brings the least amount of dependencies in? Thanks
解决方案
You could try RestAssured. Not sure if it's dependencies fit better to your needs. It can be used to test API's and therefore it can be used as well as a simple REST client.
推荐阅读
- javascript - 在 Django 中使用 Barba
- amazon-web-services - 如何通过 Ansible 连接到“VyOS on AWS”路由器?
- html - 无法在 IE11 上查看 ::before 中的伪元素内容
- javascript - TypeError:没有'new'就不能调用类构造函数ESLintWebpackPlugin
- pandas - 如何使用熊猫在同一组中加入两个多对多的数据框?
- c++ - 无法获取 C++ 字符串的子字符串的正确位置
- c# - WMPLib,正在播放曲目,我猜非常基本......但仍然失败?
- android - Android 北极狐的 InvocationTargetException | M1 Apple 硅片上的 2020.3.1 arm64
- python - 如何将 pandas.core.series.Series 转换为字符串?
- sql-server - Azure DataFactory - 数据库操作因“无效的对象名称”而失败