2017-05-03 1 views
-1

이 오류와 관련된 많은 게시물을 보았지만 저에게 적합한 해결책을 찾지 못했습니다. 그래서 다시 게시 할 예정입니다.ftp 서버에 연결하는 중 연결 시간 초과 예외가 발생했습니다

아파치 공유 라이브러리를 사용하여 ft.drivehq.com에서 파일을 업로드하려고합니다. 방화벽 설정과 같은 많은 솔루션을 시도했습니다. 그 솔루션 중 아무 것도 작동하지 않습니다.

이것은 양식 필드에서 파일 이름을 가져 와서 ftp connect 메소드 및 upload file 메소드를 호출하는 코드입니다.

protected void processRequest(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException { 

    ismultipart = ServletFileUpload.isMultipartContent(request); 

    response.setContentType("text/html"); 
    PrintWriter out = response.getWriter(); 

    if(!ismultipart) 
    { 
     out.println("<html>"); 
     out.println("<head>"); 
     out.println("<title>servlet upload</title>"); 
     out.println("</head>"); 
     out.println("<body>"); 
     out.println("<p>no file upload</p>"); 
     out.println("</body>"); 
     out.println("</html>"); 
     return; 

    } 

    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); 
    fileItemFactory.setSizeThreshold(1 * 1024 * 1024); 
    fileItemFactory.setRepository(new File(TMP_DIR_PATH)); 

    ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory); 

    Connection con = null; 
    PreparedStatement pstm = null; 
    PreparedStatement pstm1 = null; 
    PreparedStatement pstm2 = null; 
    PreparedStatement pstm3 = null; 

    try { 
     /* 
     * Parse the request 
     */ 
     con = Dbconnector.getConnection(); 
     List items = uploadHandler.parseRequest(request); 
     Iterator itr = items.iterator(); 
     String fileName = ""; 
     FileItem item = (FileItem) itr.next(); 
     System.out.println("item "+item); 
     String fName = item.getName(); 
     System.out.println("fname " + fName); 

     fileName = (String) item.getName();  
     System.out.println("filename " + fileName);  


     int x = fileName.lastIndexOf('\\'); 
     String fN = fileName.substring(x + 1, fileName.length()); 
     System.out.println(fN); 
     SimpleFTPClient client = null; 

     \\table to retrieve drivehq login details 
     String sq1 = "select * from adserver"; 

     pstm3 = con.prepareStatement(sq1); 
     ResultSet rs1 = pstm3.executeQuery(); 
     String user = ""; 
     String cld = ""; 
     while (rs1.next()) { 
      client = new SimpleFTPClient(); 
      cld = rs1.getString("host_name"); 
      user = rs1.getString("username"); 
      client.setHost(rs1.getString("host_name")); 
      client.setUser(rs1.getString("username")); 
      client.setPassword(rs1.getString("password")); 
      client.setRemoteFile("pdp_cloud"); 
      client.setport(21); 

      boolean log = client.connect(); 
      System.out.println(log); 
      if (log) { 
       if(client.uploadFile(item.getInputStream())) { 

        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + user); 
        String sq2 = "insert into upload (file_name,date,file_data)values(?,?,?)"; 
        pstm1 = con.prepareStatement(sq2); 
        pstm1.setString(1, fileName); 
        //pstm1.setString(2, "not set"); 
        // pstm1.setString(3, "not set"); 
        pstm1.setString(2, dateNow); 
        pstm1.setBinaryStream(3, item.getInputStream(), item.getSize()); 
        pstm1.execute(); 

       } else { 
        System.out.println(">>>>>>else"); 

       } 
      } else { 
       System.out.println("not connected"); 
      } 

     } 
     response.sendRedirect("CreateBlocks.html?msg=File Uploaded.."); 


    } catch (Exception ex) { 
     ex.printStackTrace(); 
     response.sendRedirect("UploadFile.html?msg=Cloud Not Connected"); 
     // log("Error encountered while uploading file", ex); 
    } 



} 

이것은 연결 방법과 업로드 및 다운로드 파일 방법이있는 클래스입니다. 여기에 실제 사용자 이름과 암호를 사용하지 마십시오.

 public class SimpleFTPClient { 

    /** The URL connection object */ 
    private URLConnection m_client; 
    /** The FTP host/server to be connected */ 
    private String host; 
    /** The FTP user */ 
    private String user; 
    /** The FTP user’s password */ 
    private String password; 
    /** The remote file that needs to be uploaded or downloaded */ 
    private String remoteFile; 
    /** The previous error message triggered after a method is called */ 
    private String erMesg; 
    /** The previous success message after any method is called */ 
    private String succMesg; 
    /**set port number */ 
    private int port; 

    public SimpleFTPClient() { 
    } 

    /** Setter method for the FTP host/server */ 
    public void setHost(String host) { 
     this.host = host; 
    } 

    /** Setter method for the FTP user */ 
    public void setUser(String user) { 
     this.user = user; 
    } 

    /** Setter method for the FTP user’s password */ 
    public void setPassword(String p) { 
     this.password = p; 
    } 

    /** Setter method for the remote file, this must include the sub-directory path relative 
    to the user’s home directory, e.g you’e going to download a file that is within a sub directory 
    called "sdir", and the file is named "d.txt", so you shall include the path as "sdir/d.txt" 
    */ 
    public void setRemoteFile(String d) { 
     this.remoteFile = d; 
    } 

    /** The method that returns the last message of success of any method call */ 
    public synchronized String getLastSuccessMessage() { 
     if (succMesg == null) { 
      return ""; 
     } 
     return succMesg; 
    } 

    /** The method that returns the last message of error resulted from any exception of any method call */ 
    public synchronized String getLastErrorMessage() { 
     if (erMesg == null) { 
      return ""; 
     } 
     return erMesg; 
    } 

    /**method to set port number for host */ 
    public void setport(int p) 
    { 
     this.port = p; 
    } 

    /** The method that handles file uploading, this method takes the absolute file path 
    of a local file to be uploaded to the remote FTP server, and the remote file will then 
    be transfered to the FTP server and saved as the relative path name specified in method setRemoteFile 
    @param localfilename – the local absolute file name of the file in local hard drive that needs to 
    FTP over 
    */ 
    public synchronized boolean uploadFile(InputStream is) { 
    //public synchronized boolean uploadFile(String localfilename) { 
     try { 

     // InputStream is = new FileInputStream(localfilename); 
      BufferedInputStream bis = new BufferedInputStream(is); 
      OutputStream os = m_client.getOutputStream(); 
      BufferedOutputStream bos = new BufferedOutputStream(os); 
      byte[] buffer = new byte[1024]; 
      int readCount; 

      while ((readCount = bis.read(buffer)) > 0) { 
       bos.write(buffer, 0, readCount); 
      } 
      bos.close(); 

      this.succMesg = "Uploaded!"; 

      return true; 
     } catch (Exception ex) { 
      ex.printStackTrace(); 
      StringWriter sw0 = new StringWriter(); 
      PrintWriter p0 = new PrintWriter(sw0, true); 
      ex.printStackTrace(p0); 
      erMesg = sw0.getBuffer().toString(); 

      return false; 
     } 
    } 

    /** The method to download a file and save it onto the local drive of the client in the specified absolut path 
    @param localfilename – the local absolute file name that the file needs to be saved as */ 
    public synchronized boolean downloadFile(String localfilename) { 
     try { 
      InputStream is = m_client.getInputStream(); 
      BufferedInputStream bis = new BufferedInputStream(is); 
      System.out.println(">>>>>>>>>>>"+localfilename); 
      OutputStream os = new FileOutputStream(localfilename); 
      BufferedOutputStream bos = new BufferedOutputStream(os); 

      byte[] buffer = new byte[1024]; 
      int readCount; 

      while ((readCount = bis.read(buffer)) > 0) { 
       bos.write(buffer, 0, readCount); 
      } 
      bos.close(); 
      is.close(); // close the FTP inputstream 
      this.succMesg = "Downloaded!"; 

      return true; 
     } catch (Exception ex) { 
      ex.printStackTrace(); 
      StringWriter sw0 = new StringWriter(); 
      PrintWriter p0 = new PrintWriter(sw0, true); 
      ex.printStackTrace(p0); 
      erMesg = sw0.getBuffer().toString(); 

      return false; 
     } 
    } 

    /** The method that connects to the remote FTP server */ 
    public synchronized boolean connect() { 
     try { 
      URL url = new URL("ftp://" + user + ":" + password + "@" + host + ":" + port + "/" + remoteFile); 
      m_client = url.openConnection(); 
      System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>.."+"ftp://" + user + ":" + password + "@" + host + "/" + remoteFile); 
      return true; 

     } catch (Exception ex) { 
      ex.printStackTrace(); 
      StringWriter sw0 = new StringWriter(); 
      PrintWriter p0 = new PrintWriter(sw0, true); 
      ex.printStackTrace(p0); 
      erMesg = sw0.getBuffer().toString(); 
      return false; 
     } 
    } 

가끔 내가 ..이 문에

OutputStream os = m_client.getOutputStream(); 

하는 오류를 얻을이 오류 로그입니다 -

java.net.ConnectException: Connection timed out: connect 
    at java.net.DualStackPlainSocketImpl.connect0(Native Method) 
    at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source) 
    at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source) 
    at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source) 
    at java.net.AbstractPlainSocketImpl.connect(Unknown Source) 
    at java.net.PlainSocketImpl.connect(Unknown Source) 
    at java.net.Socket.connect(Unknown Source) 
    at java.net.Socket.connect(Unknown Source) 
    at sun.net.ftp.impl.FtpClient.doConnect(Unknown Source) 
    at sun.net.ftp.impl.FtpClient.tryConnect(Unknown Source) 
    at sun.net.ftp.impl.FtpClient.connect(Unknown Source) 
    at sun.net.ftp.impl.FtpClient.connect(Unknown Source) 
    at sun.net.www.protocol.ftp.FtpURLConnection.connect(Unknown Source) 
    at sun.net.www.protocol.ftp.FtpURLConnection.getOutputStream(Unknown Source) 
    at pdp_cloud.SimpleFTPClient.uploadFile(SimpleFTPClient.java:87) 
    at pdp_cloud.UploadFile.processRequest(UploadFile.java:161) 
    at pdp_cloud.UploadFile.doPost(UploadFile.java:223) 
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:650) 
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:731) 
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) 
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) 
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) 
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) 
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) 
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218) 
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110) 
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506) 
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169) 
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) 
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962) 
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) 
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445) 
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1115) 
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637) 
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316) 
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) 
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) 
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) 
    at java.lang.Thread.run(Unknown Source) 

의 URL 형식이 맞습니까? 누구든지 나를 도울 수 있습니다 ..

+2

[실제 질문이 아닌 이유는 무엇입니까?] (https://meta.stackoverflow.com/questions/284236/why-is-can-someone-help-me-not-an- 실제 질문) –

+0

지금은 괜찮아요 .. –

답변

0

어떤 라이브러리를 사용하고 있습니까? org.apache.commons.net.ftp를 사용해 보셨습니까? Ftp 또는 Ftps입니까?

그래서이 시도 : 문제가 해결되지 않으면

import org.apache.commons.logging.Log; 
import org.apache.commons.logging.LogFactory; 
import org.apache.commons.net.PrintCommandListener; 
import org.apache.commons.net.ftp.FTP; 
import org.apache.commons.net.ftp.FTPClient; 
import org.apache.commons.net.ftp.FTPFile; 
import org.apache.commons.net.ftp.FTPReply; 
import org.apache.commons.net.ftp.FTPSClient; 
public class FTPMain { 
FTPClient ftp = null; 

public FTPMain(){ 

    } 

    public Object mainFTP() throws Exception { 

     try{ 

      initFTPUploader("myhost.com", "user", "pass", 8080); 
      disconnect(); 
     }catch(Exception e){ 
      String msg = "Error"; 
     } 

     return "disconnect"; 
    } 
    public void initFTPUploader(String host, String user, String pwd,int numPort) throws Exception { 
     ftp= new FTPClient(); //use new FTPSClient if is FTPS 
     ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out))); 
     int reply; 
     ftp.connect(host, numPort); 
     reply = ftp.getReplyCode(); 
     if (!FTPReply.isPositiveCompletion(reply)) { 
      ftp.disconnect(); 
      throw new Exception("Exception in connecting to FTP Server"); 
     } 
     ftp.enterLocalPassiveMode(); 
     ftp.login(user, pwd); 
     ftp.setFileType(FTP.BINARY_FILE_TYPE); 
     ftp.printWorkingDirectory(); 
     ftp.changeWorkingDirectory("/myDirectory"); 
     ftp.printWorkingDirectory(); 
     //ftp.execPBSZ(0);// use this two only if is a ftps connection 
     //ftp.execPROT("P");// use this two only if is a ftps connection 

    } 
} 

은 오류가없는 경우 "텔넷은 host.com numPort", 그래서 아마 오류가있는 쉘 명령 행을 열고 사용하려고 마지막 코드에 오류가있는 경우 연결하려는 출력 포트가 시스템 구성에서 열려 있는지 확인하십시오.

+0

작동합니까? 내 대답을 "수락"으로 선택해 주실 수 있습니까? 덕분에 –

+0

네, 성공했습니다 .. –

관련 문제