Home > Java > javaTutorial > How to Implement Http Basic Authentication in Java using HttpClient?

How to Implement Http Basic Authentication in Java using HttpClient?

Mary-Kate Olsen
Release: 2024-11-11 20:45:03
Original
557 people have browsed it

How to Implement Http Basic Authentication in Java using HttpClient?

Http Basic Authentication in Java Using HttpClient

To mimic the functionality of the provided curl command, you can employ the following techniques using Commons HttpClient.

Commons HttpClient 3.0.1

The issue with the provided code is that the setDoAuthentication method is deprecated in Commons HttpClient 3.0.1. Instead, you can manually set the authentication header:

post.setRequestHeader("Authorization", "Basic " + Base64.encodeBase64String((username + ":" + password).getBytes(ENCODING)));
Copy after login

Commons HttpClient 4.0.1

For Commons HttpClient 4.0.1, you can use the following code to perform basic authentication:

String encoded = Base64.getEncoder().encodeToString((user + ":" + pwd).getBytes());
HttpPost httpPost = new HttpPost("http://host:post/test/login");
httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + encoding);

System.out.println("executing request " + httpPost.getRequestLine());
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
Copy after login

The above is the detailed content of How to Implement Http Basic Authentication in Java using HttpClient?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template