0

So i've been searching around the web for awhile. I was wondering what the best approcah would be for POSTing to a https url with a JSON payload? I have this working code just to get a basic token using a GET to a HTTPS url. Could this be modified? Or is there a better overall approach to this for posting data?

example payload: {"state" : "ok"}

java code:

public static void changeHealthState(final String token) throws NoSuchAlgorithmException, KeyManagementException, IOException {
    final TrustManager[] trustManager = new TrustManager[] { new X509TrustManager() {
        public void checkClientTrusted(final X509Certificate[] chain, final String authType) {
        }

        public void checkServerTrusted(final X509Certificate[] chain, final String authType) {
        }

        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    }};

    SSLContext sslContext;
    sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, trustManager, new java.security.SecureRandom());

    final javax.net.ssl.SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

    Authenticator.setDefault(new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(token, "".toCharArray());
        }
    });

    final URLConnection urlConnection = new URL(
            "myurl").openConnection();

    ((HttpsURLConnection) urlConnection).setSSLSocketFactory(sslSocketFactory);
    int responseCode = ((HttpsURLConnection) urlConnection).getResponseCode();
    StringBuffer result = new StringBuffer();

    final InputStream input;

    BufferedReader bufferedReader;

    if (responseCode == 200) {
        input = urlConnection.getInputStream();
    } else {
        input = null;
    }

    bufferedReader = new BufferedReader(new InputStreamReader((input)));

    String line = "";

    while ((line = bufferedReader.readLine()) != null) {
        result.append(line);
    }
    String output = null;
    output = result.toString();
    System.out.println(output);
    input.close();
}
David Dennis
  • 702
  • 2
  • 9
  • 26
  • Does this help you: https://stackoverflow.com/questions/14561293/sending-post-data-to-https-without-ssl-cert-verification-with-apache-httpclient -- esp. using HttpPost.setEntity()? – Heiko Jakubzik Nov 16 '17 at 19:33
  • @HeikoJakubzik: that's for apache HttpClient, which is separate and quite different from standard Http[s]UrlConnection. Instead try https://stackoverflow.com/questions/4205980/java-sending-http-parameters-via-post-method-easily https://stackoverflow.com/questions/21404252/post-request-send-json-data-java-httpurlconnection https://stackoverflow.com/questions/44305351/send-data-in-request-body-using-httpurlconnection – dave_thompson_085 Nov 16 '17 at 21:50

0 Answers0