试图在JAVA中连接gmail并从服务器获取收件箱?

时间:2012-11-01 05:55:05

标签: java sockets ssl imap jsse

我正在尝试连接gmail并从服务器获取收件箱。我可以连接到Gmail并登录我的帐户。当我将它们发送到套接字

output.println( "A01 lOGIN " + userName + " " + password );
output.flush();

我可以从套接字获得响应。但是当我发送新东西时:

output.println( "A02 SELECT INBOX");
JOptionPane.showMessageDialog( null,"Before Flush");
output.flush();
JOptionPane.showMessageDialog( null,"After Flush");

并尝试从套接字获取响应:

JOptionPane.showMessageDialog( null,in.nextLine());
JOptionPane.showMessageDialog( null,"After nextLine()");

它没有显示任何消息对话框,等待将近5分钟。 5分钟后,它显示空消息对话框(不显示最后一条消息)。我找不到任何解决方案。有谁知道问题是什么?

public static void main(String[] args) {

 // open SSLSocket connection to server and send login
    try { 

       // obtain SSLSocketFactory for creating SSLSockets
       SSLSocketFactory socketFactory = 
          ( SSLSocketFactory ) SSLSocketFactory.getDefault();

       // create SSLSocket from factory
       SSLSocket socket = 
          ( SSLSocket ) socketFactory.createSocket( 
             "imap.gmail.com", 993 ); 

       // create PrintWriter for sending login to server
       PrintWriter output = new PrintWriter( 
          new OutputStreamWriter( socket.getOutputStream() ) );

       Scanner in = null;
       in = new Scanner(socket.getInputStream());

       // display response to user
       JOptionPane.showMessageDialog( null, in.nextLine());

       // prompt user for user name
       String userName = JOptionPane.showInputDialog( null,
          "Enter User Name:" );

       // prompt user for password
       String password = JOptionPane.showInputDialog( null,
          "Enter Password:" );

       output.println( "A01 lOGIN " + userName + " " + password );
       output.flush();

       // display response to user
       JOptionPane.showMessageDialog( null, in.nextLine());
       JOptionPane.showMessageDialog( null, in.nextLine());

       output.println( "A02 SELECT INBOX");
       JOptionPane.showMessageDialog( null,"Before Flush");
       output.flush();
       JOptionPane.showMessageDialog( null,"After Flush");

       /*
        * It waits in nextLine() and it does not show anything
        * Because of waiting, It does not show After nextLine() message Dialog
        * But after 5 minutes, It shows a message dialog with null string
        */
       JOptionPane.showMessageDialog( null,in.nextLine());
       JOptionPane.showMessageDialog( null,"After nextLine()");

       // clean up streams and SSLSocket
       output.close();
       in.close();
       socket.close();

    } // end try

    // handle exception communicating with server
    catch ( IOException ioException ) { 
       ioException.printStackTrace(); 
    } 

    // exit application
    finally {
       System.exit( 0 );
    }
}

0 个答案:

没有答案