I am trying to reproduce the following curl command using Java:
curl -v -u user:pass http://myapp.com/api
This command returns some JSON data.
My buggy Java implementation is as follows:
@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;
}
Yet, when I execute the test, it returns a org.springframework.web.client.HttpClientErrorException: 401 Unauthorized
exception.
When logging in DEBUG
, I see no information about the authentication...
What am I doing wrong while setting the authentication credentials?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…