尝试将基本身份验证添加到 restTemplate
我遇到的问题是我无法初始化:(代码片段中的两个导入)
HttpClient client = new HttpClient();
此代码在编译错误中解决(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
);
运行这个得到异常:
> 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