我正在尝试使用 Java 重现以下 curl 命令:
curl -v -u user:pass http://myapp.com/api
此命令返回一些 JSON 数据。
我的错误Java实现如下:
@Test
public void callTest() {
RestTemplate restTemplate = createRestTemplate("user", "pass");
URI uri = new URI("http://myapp.com/api");
String res = restTemplate.getForObject(uri, String.class);
}
private static RestTemplate createRestTemplate(String username, String password) {
UsernamePasswordCredentials cred = new UsernamePasswordCredentials(username, password);
BasicCredentialsProvider cp = new BasicCredentialsProvider();
cp.setCredentials(AuthScope.ANY, cred);
DefaultHttpClient client = new DefaultHttpClient();
client.setCredentialsProvider(cp);
ClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(client);
RestTemplate restTemplate = new RestTemplate(factory);
// set the media types properly
return restTemplate;
}
然而,当我执行测试时,它返回一个org.springframework.web.client.HttpClientErrorException: 401 Unauthorized
异常。
登录时DEBUG
,我看不到有关身份验证的信息...
设置身份验证凭据时我做错了什么?