I am getting java.net.SocketTimeoutException while executing java file transfer program using jcraft-Jsch api but working with other API like apache with same connection details.
I am able to connect to FTP server using any FTP client software.
Program using Jsch API
Dependency used:
<dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.55</version> </dependency>
Program using Jsch:
JSch jsch = new JSch(); jsch.setKnownHosts("/Users/test/.ssh/known_hosts"); Session jschSession = jsch.getSession("username", "remoteHost","port"); jschSession.setPassword("password"); jschSession.connect(); //Failing here and connection is not established ChannelSftp channelSftp=jschSession.openChannel("sftp"); channelSftp.connect(); String localFile = "src/main/resources/sample.txt"; String remoteDir = "remote_sftp_test/"; channelSftp.put(localFile, remoteDir + "jschFile.txt"); channelSftp.exit();
Note: I am able to connect to FTP server using any client software but not with above program
Program using apache-net
Working program with same connection details using apache net api:
Dependency used:
<dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <version>3.6</version> </dependency>
Program:
String host="XXXXX"; int port = 21; String user = "username"; String pass = "pwd"; FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(server, port); ftpClient.login(user, pass); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); // APPROACH #1: uploads first file using an InputStream File firstLocalFile = new File("C://internal/test.pdf"); String firstRemoteFile = "test.pdf"; InputStream inputStream = new FileInputStream(firstLocalFile); System.out.println("Start uploading first file"); boolean done = ftpClient.storeFile(firstRemoteFile, inputStream); inputStream.close(); if (done) { System.out.println("The first file is uploaded successfully."); } } catch (IOException ex) { System.out.println("Error: " + ex.getMessage()); ex.printStackTrace(); } catch (Exception ex) { System.out.println("Error: " + ex.getMessage()); ex.printStackTrace(); } finally { try { if (ftpClient.isConnected()) { ftpClient.logout(); ftpClient.disconnect(); } } catch (IOException ex) { ex.printStackTrace(); } }