I have following CURL command which works fine using -k options, which means: insecure, Allow connections to SSL sites without certs.
I am using WSO2 API Manager
tool version 1.9.1
.
curl -k -d "grant_type=password&username=test&password=test" -H
"Authorization: Basic XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX,
Content-Type: application/x-www-form-urlencoded"
https://XXX.XXX.XXX.XXX:8243/token
Now I wanted to achieve the same using the RestTemplate in Spring, so I developed the following code so far, and it's giving me a Connection refused error:
My Code
@Before
public void testBefore(){
disableSslVerification();
}
private static void disableSslVerification() {
try {
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
}
};
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
}
@Test public void testGetTokenFromWSo2(){ String url = "https://XXXXXXXXXXX:8243/token";
MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
map.add("grant_type", "password");
map.add("username", "test");
map.add("password", "test");
HttpHeaders headers =new HttpHeaders();
headers.add("Authorization", "Basic XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
headers.add("Content-Type", "application/x-www-form-urlencoded");
RestTemplate restTemplate = new RestTemplate();
HttpEntity<String> entity = new HttpEntity<String>(headers);
HttpEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class, map);
System.out.println("RESPONSE : "+response.getBody());
}
The error I see
org.springframework.web.client.ResourceAccessException: I/O error on GET request for "https://XXXXXXXXXXXXXX:8243/token":Connection refused: connect; nested exception is java.net.ConnectException: Connection refused: connect
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:567)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:520)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:463)