Java 测试URL地址是否能正常连接的代码
程序员文章站
2024-03-13 14:59:51
java 测试url地址是否能正常连接
public static int testwsdlconnection(string address) throws e...
java 测试url地址是否能正常连接
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是否可用或者可打开的代码
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; } }