简体   繁体   English

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

[英]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.

相关问题 Spring Boot:使用具有基本身份验证的安全 API - Spring Boot: Consume Secured API with Basic Authentication REST API 使用 spring restTemplate 的基本身份验证 - Basic authentication for REST API using spring restTemplate 如何使用CXF框架使用受HTTP基本身份验证保护的Web服务? - How do I consume a web service protected with HTTP basic authentication using the CXF framework? 登录/使用 Api 休息,Spring Security 基本身份验证不起作用 - Login/Consume Api rest with Spring Security basic Auth not Working CXF RESTful Client - 如何在没有Spring的情况下进行基本的http身份验证? - CXF RESTful Client - How to do basic http authentication without Spring? 我在 spring boot 中放置了基本身份验证,但是我们如何在没有身份验证登录的情况下访问一些 Api - I put basic authentication in spring boot but how we access some Api without authentication login 如何调用需要基本身份验证的Rest API? - How to call rest api that require basic authentication? 如何避免每次都点击REST身份验证API消耗实际服务 - How to avoid hitting REST Authentication API everytime to consume actual Service android downloadManager如何做http基本身份验证 - how android downloadManager do http basic authentication Spring Security Rest基本身份验证 - Spring Security Rest Basic authentication
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM