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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15462128/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 19:41:24  来源:igfitidea点击:

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

javaspringresthttp-headersbasic-authentication

提问by Nimrod007

trying to add basic auth to restTemplate

尝试将基本身份验证添加到 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)

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

1) what is the problem ?

1)有什么问题?

2) Am i importing the wrong class ?

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

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

回答by Nimrod007

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 !

它有效!

回答by zagyi

If you use the Apache HttpClient, instantiate DefaultHttpClient, because HttpClientis just an interface:

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

HttpClient httpclient = new DefaultHttpClient();

See the documentation on using various authentication schemes with HttpClienthere.

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

回答by Subhasish

We can use it in Spring boot in the below manner :

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

   @SpringBootApplication

public class Application implements CommandLineRunner{

公共类应用程序实现 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;
}

}

}