使用RestTemplate进行基本身份验证

使用RestTemplate进行基本身份验证

本文介绍了使用RestTemplate进行基本身份验证-编译错误-构造函数HttpClient()不可见的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试向restTemplate添加基本身份验证

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

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

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

1)有什么问题?

2)我输入了错误的类吗?

2) Am i importing the wrong class ?

我的代码段:

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

推荐答案

最后,使用以下命令可以更轻松地运行基本身份验证:

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

restTemplate.exchange()

而不是

restTemplate.getForObject()

我的代码段:

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

它有效!

这篇关于使用RestTemplate进行基本身份验证-编译错误-构造函数HttpClient()不可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 08:36