繁体   English   中英

我们如何在spring中使用Http基本身份验证来使用rest api?

[英]How do we consume rest api with Http basic authentication in spring?

我想从带有 http 基本身份验证的 url 中使用 rest api,它返回一个大的 json,然后我想在没有 POJO 的情况下解析该 json 以从中获取一些值。 我如何在 java spring 中实现这一点?

我知道这是一个常见问题,但我无法找到适合我的正确解决方案。

请帮助我的人。

使用 Apache HttpClient,从以下 URL 复制了以下截取的客户端代码。 评论是我自己加的。

https://www.baeldung.com/httpclient-4-basic-authentication

HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION);

// Combine the user and password pair into the right format
String auth = DEFAULT_USER + ":" + DEFAULT_PASS;

// Encode the user-password pair string in Base64
byte[] encodedAuth = Base64.encodeBase64(
  auth.getBytes(StandardCharsets.ISO_8859_1));

// Build the header String "Basic [Base64 encoded String]"
String authHeader = "Basic " + new String(encodedAuth);

// Set the created header string as actual header in your request
request.setHeader(HttpHeaders.AUTHORIZATION, authHeader);

HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(request);

int statusCode = response.getStatusLine().getStatusCode();
assertThat(statusCode, equalTo(HttpStatus.SC_OK));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM