Search code examples
androidspringsslresttemplate

How to use SSL for my android spring resttemplate


I've been using Spring's RestTemplate to access my webservice, but now i need to use ssl. Ive been searching and found a few examples but none that worked (I had a lot of truble with deprecated functions where i cant figure out)

Here is how i use it so far

RestTemplate restTemplate = new RestTemplate();
// Add the String message converter
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
// Make the HTTP GET request, marshaling the response to a String
String result = restTemplate.getForObject(urlQuery, String.class, "GetUnit/" + tM.getDeviceId());
}

Gradle

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.2.1'
    compile 'com.android.support:support-v4:23.2.1'
    compile 'org.springframework.android:spring-android-rest-template:2.0.0.M3'
    compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.8.1'
}

how do i make this do ssl?


Solution

  • I ended up throwing away Spring. i was unable to find a solution using Spring.

    so now i rely on HttpsUrlConnection and using gson for sending objects

    public String GetUnit(String url) {
            String result = null;
            HttpURLConnection urlConnection = null;
            try {
                URL requestedUrl = new URL(url);
                urlConnection = (HttpURLConnection) requestedUrl.openConnection();
                if (urlConnection instanceof HttpsURLConnection) {
                    ((HttpsURLConnection) urlConnection).setSSLSocketFactory(sslContext.getSocketFactory());
                    ((HttpsURLConnection) urlConnection).setHostnameVerifier(new BrowserCompatHostnameVerifier());
                }
                urlConnection.setRequestMethod("GET");
                urlConnection.setConnectTimeout(1500);
                urlConnection.setReadTimeout(1500);
                lastResponseCode = urlConnection.getResponseCode();
                result = IOUtil.readFully(urlConnection.getInputStream());
            } catch (Exception ex) {
                result = ex.toString();
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
            }
            return result;
        }