2

I am new to java and wanted check the equivalent of -k in java rest client. when i do a curl with -k it works for me on a linux machine. i made client in java .

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class restposts {

// http://localhost:8080/RESTfulExample/json/product/post
public static void main(String[] args) {

  try {

    URL url = new URL("https://test");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json");
    conn.setRequestProperty("abcd", "defg");

    String input = "{\"status_id\":1,\"comment\":\" Java\"}";

    OutputStream os = conn.getOutputStream();
    os.write(input.getBytes());
    os.flush();

    if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
        throw new RuntimeException("Failed : HTTP error code : "
            + conn.getResponseCode());
    }

    BufferedReader br = new BufferedReader(new InputStreamReader(
            (conn.getInputStream())));

    String output;
    System.out.println("Output from Server .... \n");
    while ((output = br.readLine()) != null) {
        System.out.println(output);
    }

    conn.disconnect();

  } catch (MalformedURLException e) {

    e.printStackTrace();

  } catch (IOException e) {

    e.printStackTrace();

 }

}

}

and it gives me error like

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1902)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:276)

I am not sure on this error. Is there a way i can do a suppress this error or is there anything I am missing

Bhaskar Mishra
  • 3,012
  • 7
  • 23
  • 34
  • 2
    Check this question: http://stackoverflow.com/questions/19723415/java-overriding-function-to-disable-ssl-certificate-check – bcholmes Jan 13 '16 at 16:19
  • User `HttpsURLConnection` instead of `HttpURLConnection` would be my guess. I assume the connection doesn't really need an type of authentication. – SGM1 Jan 13 '16 at 16:20

1 Answers1

3

I got it working by following the below code. Also I was trying to send user information as headers which was incorrect. I was not able to find method to send user and apikey so i encoded the "user:key" into Base 64 () and added them into header. So if you want to send a basic http authentication with user:apikey . You may use the below code.

Here is the code for a sample POST request:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.*;
import javax.net.ssl.*; 
import java.security.*;
import java.security.cert.*;



public class restcalls {



    public static void disableCertificateValidation() {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() { 
                return new X509Certificate[0]; 
            }

            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

            }
        }
        };
    // Ignore differences between given hostname and certificate hostname
        HostnameVerifier hv = new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        // Install the all-trusting trust manager
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            HttpsURLConnection.setDefaultHostnameVerifier(hv);
        } catch (Exception e) {
            // Do nothing
        }
    }
    public static void main(String[] args) {

        try {

            URL url = new URL("https://tes");

            disableCertificateValidation();
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Authorization","Basic getyouruser:keyencodedintobase64useanylibraryordoonline==");

            String input = "{\"status_id\":1,\"comment\":\"Post request\"}";

            OutputStream os = conn.getOutputStream();
            os.write(input.getBytes());
            os.flush();

            if (conn.getResponseCode() != HttpsURLConnection.HTTP_OK) {
                    throw new RuntimeException("Failed : HTTP error code : "
                        + conn.getResponseCode() + conn.getResponseMessage());
            }

            BufferedReader br = new BufferedReader(new InputStreamReader(
                        (conn.getInputStream())));

            String output;
            System.out.println("Output from Server .... \n");
            while ((output = br.readLine()) != null) {
                    System.out.println(output);
            }

            conn.disconnect();

        } catch (MalformedURLException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

    }

    } 
}
Bhaskar Mishra
  • 3,012
  • 7
  • 23
  • 34