簡體   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