Reputation: 63
I have this, code which does a post request from an xml (soap) file
public static SoapEnv doRequest(String url, String requestPath) throws IOException, InterruptedException {
String requestBody = inputStreamToString(new FileInputStream(new File(requestPath)));
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.POST(HttpRequest.BodyPublishers.ofString(requestBody))
.build();
HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString());
XmlMapper xmlMapper = new XmlMapper();
SoapEnv value = xmlMapper.readValue(response.body(), SoapEnv.class);
return value;
}
and it works.
But now I need to add basic authentication. I have login and password.
How can I do this programmatically?
Upvotes: 0
Views: 1177
Reputation: 1666
You just need to add a header with the Base64 encoded authentication credentials separated by a colon ":".
Something like this;
String auth = "username:password";
String base64Creds = Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8));
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Authorization", "Basic " + base64Creds)
.POST(HttpRequest.BodyPublishers.ofString(requestBody))
.build();
Upvotes: 2