使用RestTemplate进行基本身份验证 - 编译错误 - 构造函数HttpClient()不可见

Nim*_*007 3 java rest spring basic-authentication http-headers

试图将基本身份验证添加到restTemplate

我遇到的问题是我无法初始化:(在代码片段中都有导入)

HttpClient client = new HttpClient();
Run Code Online (Sandbox Code Playgroud)

此代码解决了编译错误(没有建议eclipse可以解决此问题)

1)问题是什么?

2)我输入了错误的课程吗?

我的代码片段:

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
 );
Run Code Online (Sandbox Code Playgroud)

运行此获取异常:

> 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
Run Code Online (Sandbox Code Playgroud)

Nim*_*007 12

最后使用以下方法更容易运行基本身份验证:

restTemplate.exchange()
Run Code Online (Sandbox Code Playgroud)

并不是

restTemplate.getForObject()
Run Code Online (Sandbox Code Playgroud)

我的代码片段:

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);
Run Code Online (Sandbox Code Playgroud)

它的工作原理!