当前位置: 首页 > 知识库问答 >
问题:

用java检查internet连接

唐弘厚
2023-03-14

我希望代码检查互联网连接,直到连接可用。如果互联网断开,我不希望执行停止。

关于堆栈溢出,很少有检查internet连接的解决方案,但是如果我使用这些解决方案,一段时间后我会得到堆栈溢出错误。

private static void checkNetConnectivity() 
 {
     Socket sock = new Socket();
     InetSocketAddress addr = new InetSocketAddress("www.google.com",80);
     try{
        sock.connect(addr,3000);
        System.out.println("connected");
     }catch(Exception e){
         System.out.println("not connected");
     } 


 }

我从以下函数调用该方法:

public static void downloadEmails(String protocol, String host, String port, String username, String password)
{
    Properties props = new Properties();
    Folder inbox = null;

    MimeBodyPart bp = null;
    String mail_subject = null, mail_body = null;
    int i;


    props.setProperty("mail.store.protocol", "imaps");
    //props.put("mail.pop3.host", host);
    //props.put("mail.pop3.port", port);
    //props.put("mail.pop3.starttls.enable", "true");
    try
    {
        do
        {
            checkNetConnectivity();
        Session session = Session.getInstance(props);
        //session.setDebug(true);
        Store store = session.getStore(protocol);
        store.connect(host, username, password);


        inbox = store.getFolder("INBOX");
        inbox.open(Folder.READ_WRITE);// READ_WRITE mode is compulsory if you want to set the SEEN flag.


            cnt = 0;
            Flags seen = new Flags(Flags.Flag.SEEN);
            FlagTerm unseenFlagTerm = new FlagTerm(seen, false);
            Message msg[] = inbox.search(unseenFlagTerm);
            System.out.println("No of unseen messages : " + msg.length);
            if (msg.length > 0) 
            {
                for (i = 0; i < msg.length; i++) 
                {
                    System.out.println("Serial No :" + i);
                    Address[] in = msg[i].getFrom();
                    for (Address address : in) 
                    {
                        System.out.println("FROM:" + address.toString());
                        //String mail_address = address.toString();
                    }
                    System.out.println("SENT DATE: " + msg[i].getSentDate());
                    System.out.println("SUBJECT: " + msg[i].getSubject());
                    mail_subject = msg[i].getSubject();
                    Date date = msg[i].getSentDate();
                    DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                    String mail_sent_date = df.format(date);
                    System.out.println("Sent date = "+ mail_sent_date);


                    String str1[] = mail_subject.split("\\|");
                    int sub_delimiter_count = str1.length - 1; //count of delimiter for validating email subject


                    if (str1[0].equals("1001") && sub_delimiter_count == 3 ) 
                    {

                        System.out.println("Subject line valid.");

                        Object content = msg[i].getContent();

                        if (content instanceof String) 
                        {
                            String body = (String) content;
                            mail_body = body;

                            boolean isValid = new ReadMail().ValidateMail(mail_body);

                            if(isValid)
                            {
                                System.out.println("Email body in proper format.");
                            }
                            else
                            {
                                System.out.println("Email not in proper format.\nIgnoring...");
                                continue;
                            }
                        }
                        else if (content instanceof Multipart) 
                        {
                            System.out.println("This is MultiPart");
                            MimeMultipart mp = (MimeMultipart) msg[i].getContent();
                            bp = (MimeBodyPart) mp.getBodyPart(0);
                            InputStream partInput = bp.getInputStream();
                            mail_body = new Scanner(partInput, "UTF-8").useDelimiter("\\A").next();
                        }
                        System.out.println("hhhh");
                        ReadEmail(mail_subject, mail_body, mail_sent_date);


                    }
                    else
                    {
                        System.out.println("Subect not in required format.\nIgnoring...");
                    }
                    msg[i].setFlag(Flags.Flag.SEEN, true); // for this to work INBOX or any FOLDER has to opened in READ_WRITE mode.
                 }
            } else {
                Date date = new Date();
               System.out.println("No new messages. Last checked: "+date.toString());
           }

        try {
            Thread.sleep(2000);                 //1000 milliseconds is one second.
        } catch(InterruptedException ex) {
            Thread.currentThread().interrupt();
        }
        store.close();
      }while(true); 

    }catch(Exception e)
    {
        e.printStackTrace();
        //downloadEmails(protocol,host,port,username,password);
    }

}

MessagingException:没有路由到主机:Connect;嵌套异常为:java.net.norouteToHostException:没有到主机的路由:连接在com.sun.mail.imap.imapstore.protocolconnect(imapstore.java:670)调试:setdebug:JavaMail版本1.4.7调试:getProvider()返回javax.mail.provider[STORE,imaps,com.sun.mail.imap.imap.imapsslstore,Oracle]调试imaps:mail.imap.fetchsize:16384调试imaps:时间:10个调试imaps:尝试连接到主机“outlook.office365.com”,端口993,isSSL true

在javax.mail.service.connect(service.java:295)在javax.mail.service.connect(service.java:176)在readmail.readmail.downloademails(readmail.java:323)在readmail.readmail.main(readmail.java.downloademails(readmail.java:200)在readmail.readmail.main(readmail.java:323)由以下原因造成:java.net.norouteToHostException:没有到host:connect的路connect(未知来源)位于java.net.plainsockeTimpl.connect(未知来源)位于java.net.sockssockeTimpl.connect(未知来源)位于java.net.socket.connect(未知来源)位于java.net.socket.connect(未知来源)位于java.net.socket.connect(未知来源)位于com.sun.mail.util.socketFetcher.createSocket(未知来源)位于com.sun.mail.util.socketFeter.createSocket(未知来源)位于在com.sun.mail.imap.imapstore.newimapproprotocol(imapstore.java:115).在com.sun.mail.imap.imapstore.protocolnect(imapstore.java:636).还有4个

任何帮助都将不胜感激。

共有1个答案

师增
2023-03-14

根据探员的要求。使用Sarge框架监督重试。

我将您的连接逻辑外部化为MailService类,以便能够对其进行管理。

public class MailService {


public Store connect(String protocol, String host, String username, String password) throws MessagingException{

    Properties props = new Properties();
    props.setProperty("mail.store.protocol", "imap");
    //props.put("mail.pop3.host", host);
    //props.put("mail.pop3.port", port);
    //props.put("mail.pop3.starttls.enable", "true");

    Session session = Session.getInstance(props);
    //session.setDebug(true);
    Store store = session.getStore(protocol);

    store.connect(host, username, password);

    return store;
}

}

    public static void downloadEmails(String protocol, String host, String port, String username, String password) {

    Plan failurePlan = new Plan() {
        public Directive apply(Throwable failure) {
            if (failure instanceof MessagingException) {
                // if we failed due to ConnectException, then retry five times over a minute.
                if (((MessagingException) failure).getCause() instanceof ConnectException) {
                    return Directive.Retry(5, Duration.mins(1));
                }
            }
            return Directive.Escalate;
        }

    };

    Sarge sarge = new Sarge();

    Folder inbox = null;
    MimeBodyPart bp = null;
    String mail_subject = null, mail_body = null;
    int i;


    try {

        MailService supervisedMailService = sarge.supervised(MailService.class, failurePlan);

        do {

            Store store = supervisedMailService.connect(protocol, host, username, password);

            inbox = store.getFolder("INBOX");
            inbox.open(Folder.READ_WRITE);

// ... yada yada yada ... your code
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.hall</groupId>
  <artifactId>sarge</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>SargeExample</name>
  <description>SargeExample</description>
  <dependencies>
    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>mail</artifactId>
        <version>1.4.7</version>
    </dependency>
    <dependency>
        <groupId>net.jodah</groupId>
        <artifactId>sarge</artifactId>
        <version>0.3.1</version>
    </dependency>
  </dependencies>
</project>
 类似资料:
  • 当我试着检查我的iPhone上的互联网连接时,我得到了一堆错误。有谁能帮我修好这个吗? 代码: 代码中的错误: 如果无法读取,则错误1表示: “int”不能转换为“scNetworkReachabilityFlags” 错误2&3: 找不到接受所提供参数的“init”的重载

  • 问题内容: 我正在研究Ionic Framework,并在使用Apache Cordova Network API 来检测AndroidApp中的互联网连接时遇到问题。我参考了本教程,并创建了一个演示项目,该项目运行良好。 我已按照以下步骤操作。[来自教程] 打开 复制粘贴此代码 安装Cordova插件 建立 跑 这很好 问题 从复制粘贴到并执行步骤6和7 我收到警报 之后 复制粘贴这个样子的 当

  • 问题内容: 在Raspberry Pi上安装了NodeJS,是否可以检查rPi是否通过NodeJs连接到Internet? 问题答案: 一种快速而肮脏的方法是检查Node是否可以解决: 这并不是完全万无一失,因为您的RaspPi可以连接到Internet但由于某种原因无法解析,并且您可能还需要检查以区分“无法解析”和“无法连接到名称服务器,因此连接可能下来”)。

  • 问题内容: 我想知道下面的方法是否可以检查我是否都已连接到网络,并且实际上也可以连接到互联网。 不只是连接到不允许我访问互联网的网络吗? 我认为确实如此,但我不确定100%。 谢谢 问题答案: 通过比较这篇文章中可接受的答案和您的代码,您正在做什么。随意比较代码。最安全的做法是在飞行模式下,关闭WiFi并在远离WiFi的位置进行一些测试,以确保安全。祝好运。

  • 问题内容: 你如何检查是否可以通过Java连接到Internet?一种方法是: 但是是否有更合适的方法来执行该任务,特别是如果你需要经常进行连续检查并且很有可能断开互联网连接时? 问题答案: 你应该连接到实际应用程序需要的地方。否则,你要测试是否与某个无关的地方(在这种情况下为Google)建立了连接。 特别是,如果你要尝试与Web服务进行通信,并且要控制该Web服务,则最好使用某种廉价的“获取状

  • 问题内容: 如何使用Javascript检查互联网连接?这样,我可以有一些条件说“在生产过程中使用Google缓存的JQuery版本,在开发过程中使用该版本或本地版本,具体取决于Internet连接”。 问题答案: 针对您的特定情况的最佳选择可能是: 在您的结束标记之前: 鉴于您的问题集中在jQuery上,这可能是最简单的方法。 如果您想要一个更强大的解决方案,可以尝试: 阅读有关W3C在脱机We