javarestsslget

How to resolve "java.net.SocketException: Unexpected end of file from server" when making a GET REST API call


I have a web server running on different machine. I am able to use postman client and load cert.pem and key.pem files and successfully do a get request.

Now I want to do this programmatically in Java. To do that I added the PKCS12 to the keystore as below:

keytool -importkeystore -destkeystore keystore.jks -srcstoretype PKCS12 -srckeystore keystore.p12

keytool -list -keystore keystore.jks

Now in the code I did this:

String url = "http://localhost:9443/server/api/v1/"+id+"/_history/"+history;
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();

System.setProperty("javax.net.ssl.keyStore", "/Users/rc/Downloads/test101/jks/keystore.jks");

System.setProperty("javax.net.ssl.keyStorePassword", "asdfgh");
System.setProperty("javax.net.ssl.keyStoreType", "JKS");            

con.setRequestMethod("GET");

        //add request header
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");

int responseCode = con.getResponseCode();       
System.out.println("\nSending 'GET' request to URL : " + url);      
System.out.println("Response Code : " + responseCode);

I am getting this error:

java.net.SocketException: Unexpected end of file from server at this line :
int responseCode = con.getResponseCode();


Solution

  • You are trying to connect via http://, but should use https://. Look at your URL:

    String url = "http://localhost:9443/server/api/v1/"+id+"/_history/"+history;
    

    "java.net.SocketException: Unexpected end of file" means that the server accepted and then closed the connection without sending a response. I believe port 9443 for HTTPS connection is not ready to accept HTTP connection.