[英]How do we consume rest api with Http basic authentication in spring?
I want to consume rest api from url with http basic authentication that returns a big json & then i want to parse that json without POJO to get some values out of it.我想从带有 http 基本身份验证的 url 中使用 rest api,它返回一个大的 json,然后我想在没有 POJO 的情况下解析该 json 以从中获取一些值。 How can i achieve that in java spring?我如何在 java spring 中实现这一点?
I know this is common question but i could not get proper solution that worked for me.我知道这是一个常见问题,但我无法找到适合我的正确解决方案。
Please help me someone.请帮助我的人。
Using the Apache HttpClient, the following Client Code snipped has been copied from the following URL.使用 Apache HttpClient,从以下 URL 复制了以下截取的客户端代码。 The comments have been added by myself.评论是我自己加的。
https://www.baeldung.com/httpclient-4-basic-authentication 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.