服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服务器之家 - 编程语言 - JAVA教程 - Java 测试URL地址是否能正常连接的代码

Java 测试URL地址是否能正常连接的代码

2020-06-05 15:07冬瓜茶饮料 JAVA教程

本文给大家分享两段代码分别是java测试URL地址是否能正常连接和Java检测URL是否可用或者可打开的代码,代码都很简单,有需要的朋友可以参考下

Java 测试URL地址是否能正常连接

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public static int testWsdlConnection(String address) throws Exception {
  int status = 404;
  try {
   URL urlObj = new URL(address);
   HttpURLConnection oc = (HttpURLConnection) urlObj.openConnection();
   oc.setUseCaches(false);
   oc.setConnectTimeout(3000); // 设置超时时间
   status = oc.getResponseCode();// 请求状态
   if (200 == status) {
    // 200是请求地址顺利连通。。
    return status;
   }
  } catch (Exception e) {
   e.printStackTrace();
   throw e;
  }
  return status;
 }

定义了一个int型,如果返回可200则是地址能成功连通,如果返回0或者其他则是失败。

下面再看一段关于Java检测URL是否可用或者可打开的代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package test;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.log4j.Logger;
public class CheskUrl {
  private static Logger logger = Logger.getLogger(CheskUrl.class);
  private static URL urlStr;
  private static HttpURLConnection connection;
  private static int state = -1;
  private static String succ;
  public synchronized String isConnect(String url) {
   int counts = 0;
   succ = null;
   if (url == null || url.length() <= 0) {
    return succ;
   }
   while (counts < 5) {
    try {
     urlStr = new URL(url);
     connection = (HttpURLConnection) urlStr.openConnection();
     state = connection.getResponseCode();
     if (state == 200) {
      succ = connection.getURL().toString();
     }
     break;
    } catch (Exception ex) {
     counts++; logger.info("loop :" + counts);
     continue;
    }
   }
   return succ;
  }
}

原文链接:http://www.cnblogs.com/dongguacha/archive/2016/08/19/5787709.html

延伸 · 阅读

精彩推荐