Nimrod007 Nimrod007 - 4 months ago 27
Java Question

Basic Authentication with RestTemplate - compilation error - The constructor HttpClient() is not visible

trying to add basic auth to restTemplate

problem I encounter is that i cant initialize : (with both the imports in the code snippet)

HttpClient client = new HttpClient();


This code resolves in a compilation error (with no suggestion available from eclipse to fix this issue)

1) what is the problem ?

2) Am i importing the wrong class ?

my code snippet :

import org.apache.http.client.HttpClient;
//OR (not together)
import sun.net.www.http.HttpClient;


HttpClient client = new HttpClient(); //this line dosent compile
UsernamePasswordCredentials credentials =
new UsernamePasswordCredentials("USERNAME","PASS");
client.getState().setCredentials(
new AuthScope("www.example.com", 9090, AuthScope.ANY_REALM),
credentials);
CommonsClientHttpRequestFactory commons =
new CommonsClientHttpRequestFactory(client);

RestTemplate template = new RestTemplate(commons);
SomeObject result = template.getForObject(
"http://www.example.com:9090/",SomeObject.class
);


Running this get the Exception :

> failed due to an unhandled exception: java.lang.Error: Unresolved
> compilation problems: The constructor HttpClient() is not visible
> The method getState() is undefined for the type HttpClient
> CommonsClientHttpRequestFactory cannot be resolved to a type
> CommonsClientHttpRequestFactory cannot be resolved to a type
> SomeObject cannot be resolved to a type The method
> getForObject(String, Class<SomeObject>, Object...) from the type
> RestTemplate refers to the missing type SomeObject SomeObject cannot
> be resolved to a type

Answer

in the end its much easier to run Basic Authentication using :

restTemplate.exchange()

and not

restTemplate.getForObject()

my code snippet :

private HttpHeaders createHeaders(final String username, final String password ){
    HttpHeaders headers =  new HttpHeaders(){
          {
             String auth = username + ":" + password;
             byte[] encodedAuth = Base64.encodeBase64(
                auth.getBytes(Charset.forName("US-ASCII")) );
             String authHeader = "Basic " + new String( encodedAuth );
             set( "Authorization", authHeader );
          }
       };
       headers.add("Content-Type", "application/xml");
       headers.add("Accept", "application/xml");

       return headers;
}


    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<MyClass> response;
    httpHeaders = this.createHeaders("user", "pass");

    String url = "www.example.com"
    response = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<Object>(httpHeaders), MyClass.class);

and it works !