Spring Boot RESTful Web Service to post json content to https(secure) url

I am searchign for working code sample/ snippet of spring boot to post json content to HTTPS restful web service(developed in python). Below is sample code of standlone program which does the same, But I want to do it in spring boot Restful app. I found many examples in google and stack overflows example1 example2 but these are for getrequest and not suites for what I am looking for. Someone please share full working example for "https post request using spring boot service". Thanks in advance.

import java.io.PrintStream;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import javax.net.ssl.HttpsURLConnection;

public class App{

     public static void main(String []args) throws NoSuchAlgorithmException, KeyManagementException{

        String https_url = "https://192.168.4.5:55543/books";
        String content = "{\"data\":{\"a\"}}";
        System.setProperty("javax.net.useSystemProxies", "true");

        System.setProperty("javax.net.ssl.keyStore", "C:/cert/client.jks");
        System.setProperty("javax.net.ssl.keyStorePassword", "testdev");

        System.setProperty("javax.net.ssl.trustStore", "C:/cert/server.jks");
        System.setProperty("javax.net.ssl.trustStorePassword", "testdev");

        System.setProperty("jdk.tls.client.protocals", "TLSv1.2");
        System.setProperty("https.protocals", "TLSv1.2");

        HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> { return true;});
        URL url = new URL(https_url);
        HttpsURLConnection https_con = (HttpsURLConnection) url.openConnection();

        https_con.setRequestProperty("Content-Type", "application/json");
        https_con.setRequestMethod("POST");
        https_con.setDoOutput(true);
        PrintStream ps = new PrintStream(https_con.getOutputStream());
        ps.println(content);
        ps.close();
        https_con.connect();
        https_con.getResponseCode();
        https_con.disconnect();
     }
}

1 answer

  • answered 2018-07-11 22:32 Yogen Rai

    You can find an example on Github.

    A couple of things:

    1. Just replace your https server URI in application.properties. It uses Spring Rest Template to make a call to that remote service.

    2. It has an embedded Tomcat container, so you can run your test application as a stand-alone application.

    3. You don't need to provide keystore in java config as long as they are in keychain of your system.

    Happy coding!!