Home >Java >javaTutorial >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)));
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();
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!