【问题标题】:Basic Authentication with RestTemplate - compilation error - The constructor HttpClient() is not visible使用 RestTemplate 进行基本身份验证 - 编译错误 - 构造函数 HttpClient() 不可见
【发布时间】:2013-03-05 22:07:41
【问题描述】:

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

我遇到的问题是我无法初始化:(代码 sn-p 中的两个导入)

HttpClient client = new HttpClient();

此代码在编译错误中解决(eclipse 没有提供解决此问题的建议)

1) 有什么问题?

2) 我是否导入了错误的类?

我的代码 sn-p:

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
 );

运行这个得到异常:

> 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

【问题讨论】:

    标签: java spring rest http-headers basic-authentication


    【解决方案1】:

    最终,使用以下方式运行基本身份验证要容易得多:

    restTemplate.exchange()
    

    而不是

    restTemplate.getForObject()
    

    我的代码 sn-p:

    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);
    

    它有效!

    【讨论】:

      【解决方案2】:

      如果你使用Apache HttpClient,实例化DefaultHttpClient,因为HttpClient只是一个接口:

      HttpClient httpclient = new DefaultHttpClient();
      

      请参阅有关使用HttpClient here 的各种身份验证方案的文档。

      【讨论】:

      • 当使用这个选项时我无法唤起:client.getState()
      • 那是因为它没有这个方法。尝试this example 进行客户端身份验证。
      • 或者this example 更好,因为它会将凭据预先发送到服务器。
      【解决方案3】:

      我们可以通过以下方式在 Spring boot 中使用它:

         @SpringBootApplication
      

      公共类应用程序实现 CommandLineRunner{

      private static final Logger log = LoggerFactory.getLogger(Application.class);
      
      public static void main(String[] args) {
          SpringApplication.run(Application.class, args);
      }
      
      @Override
      public void run(String... args) throws Exception {
          try{
          RestTemplate restTemplate = new RestTemplate();
          HttpHeaders httpHeaders = new HttpHeaders();
          httpHeaders = this.createHeaders();
          ResponseEntity<String> response;
          response  = restTemplate.exchange("<url>",HttpMethod.GET,new HttpEntity<Object>(httpHeaders),String.class);
          log.info(response.toString());
          }
          catch(Exception e)
          {
              System.out.println("Exception"+e);
          }
      
      
      }
      
      private HttpHeaders createHeaders(){
          HttpHeaders headers =  new HttpHeaders(){
                {            
                   set( "Authorization", "3ee140");
                }
             };
      
             return headers;
      }
      

      }

      【讨论】:

        猜你喜欢
        • 2016-08-24
        • 2013-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-22
        • 2011-03-18
        • 2012-03-11
        • 1970-01-01
        • 2014-03-26
        相关资源
        最近更新 更多