Guest User

Untitled

a guest
Jan 15th, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.41 KB | None | 0 0
  1. public static void main(String[] args) {
  2. var client = HttpClient.newBuilder()
  3. .authenticator(new Authenticator() {
  4. @Override
  5. protected PasswordAuthentication getPasswordAuthentication() {
  6. return new PasswordAuthentication("username", "password".toCharArray());
  7. }
  8. })
  9. .version(HttpClient.Version.HTTP_1_1)
  10. .build();
  11. var request = HttpRequest.newBuilder()
  12. .uri("https://service-that-needs-auth.example/")
  13. .build();
  14. client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
  15. .thenApply(HttpResponse::body)
  16. .thenAccept(System.out::println)
  17. .join();
  18. }
  19.  
  20. public static void main(String[] args) {
  21. var client = HttpClient.newBuilder()
  22. .version(HttpClient.Version.HTTP_1_1)
  23. .build();
  24. var request = HttpRequest.newBuilder()
  25. .uri("https://service-that-needs-auth.example/")
  26. .header("Authorization", basicAuth("username", "password"))
  27. .build();
  28. client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
  29. .thenApply(HttpResponse::body)
  30. .thenAccept(System.out::println)
  31. .join();
  32. }
  33.  
  34. private static String basicAuth(String username, String password) {
  35. return "Basic " + Base64.getEncoder().encodeToString((username + ":" + password).getBytes());
  36. }
Add Comment
Please, Sign In to add comment