Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.io.FileNotFoundException: while accessing REST service

I'm trying to access a web service through REST API post method and end up with FileNotFoundException

code:

public class TestService {

    static {
        disableSSLVerification();
    }

    public static void main(String[] args) {

        String[] names = {"login","seq","password"};    
        String[] values = { "admin", "2811", "admin" }; 

        String url = "https://localhost:8844/login";

        try {
            httpPost(url, names, values);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static String httpPost(String urlStr, String[] paramName, String[] paramVal) throws Exception {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        OutputStream out = conn.getOutputStream();
        Writer writer = new OutputStreamWriter(out, "UTF-8");
        for (int i = 0; i < paramName.length; i++) {
            writer.write(paramName[i]);
            writer.write("=");
            writer.write(URLEncoder.encode(paramVal[i], "UTF-8"));
            writer.write("&");
        }
        System.out.println("WRITER: " + writer);
        writer.close();
        out.close();

        if (conn.getResponseCode() != 200) {
            throw new IOException(conn.getResponseMessage());
        }

        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = rd.readLine()) != null) {
            sb.append(line);
        }
        rd.close();

        conn.disconnect();
        return sb.toString();
    }

    public static void disableSSLVerification() {

        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

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

        } };

        SSLContext sc = null;
        try {
            sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };      
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);       
    }
}

Log:

java.io.FileNotFoundException: https://localhost:8844/login
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown S
ource)
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown So
urce)
        at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unkn
own Source)

can anyone please help me to resolve this? please try to help me rather marking this one 'duplicate'.

like image 858
Nani Avatar asked Mar 16 '15 11:03

Nani


People also ask

Why do I get filenotfoundexception when opening a file in Java?

If the file is being opened exclusively by some other process, opening it for either reading or writing will cause java.io.FileNotFoundException (Access is denied) exception. Fix: Make sure that the file is not opened by any other program or processes.

How to fix filenotfoundexception (Access Denied) in Java?

Try to create a file in a subfolder, for example, C:/somedir/somefile.txt instead of the root. If the file is being opened exclusively by some other process, opening it for either reading or writing will cause java.io.FileNotFoundException (Access is denied) exception. Make sure that the file is not opened by any other program or process.

Why do I get an exception when opening a file?

This exception mainly occurs for the below reasons: 1. If the application tries to open a file, but the file is not present in the desired location. 2. While creating the file, if there is a directory with the same name as the filename then this exception occurs.

How to handle the exception when there is no such file?

There are other remedies to handle the exception: If the message of the exception tells that there is no such file or directory, then you re-verify whether you mentioned the wrong file name in the program or file exists in that directory or not.


1 Answers

  1. It's actually an HttpsURLConnection (you are opening a https:// url).

  2. That URL does not exist, try opening it in your browser. If the url exists it could be that you are using a self-signed certificate on that https host, that is rejected by java urlconnection classes(but i don't think that's the case, the exception should be different, in that case you'll need to implement a wrapper that accept the certificate anyway).

like image 135
uraimo Avatar answered Sep 20 '22 13:09

uraimo