简体   繁体   中英

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. How can i achieve that in 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. The comments have been added by myself.

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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