网络连接 以及超时处理

来源:互联网 发布:java邀请码的发放方式 编辑:程序博客网 时间:2024/04/30 02:34

public String getRequest(String surl, String encoding) throws IOException {
  String sresult = "";
  HttpURLConnection conn = null;
  try {
   URL url = new URL(surl);
   conn = (HttpURLConnection) url.openConnection();
   conn.setRequestMethod("GET");
   conn.setDoOutput(false);
    System.setProperty("sun.net.client.defaultConnectTimeout",
    "1500");
    System.setProperty("sun.net.client.defaultReadTimeout", "1500");
   InputStream in = conn.getInputStream();
   InputStreamReader isr = new InputStreamReader(in, encoding);
   char[] b = new char[255];
   StringBuffer sb = new StringBuffer();
   int len = 0;
   while ((len = isr.read(b)) > 0) {
    sb.append(b, 0, len);
   }
   sresult = sb.toString();
   isr.close();
   in.close();
   conn.disconnect();
  } catch (IOException e) {
   throw e;
  } finally {
   if (conn != null) {
    conn.disconnect();
   }
  }
  return sresult;
 }

 

Java中可以使用HttpURLConnection来请求WEB资源。 

HttpURLConnection对象不能直接构造,需要通过URL.openConnection()来获得HttpURLConnection对象,示例代码如下: 
String szUrl = "http://www.ee2ee.com/"; 
URL url = new URL(szUrl); 
HttpURLConnection urlCon = (HttpURLConnection)url.openConnection(); 
HttpURLConnection是基于HTTP协议的,其底层通过socket通信实现。如果不设置超时(timeout),在网络异常的情况下,可能会导致程序僵死而不继续往下执行。可以通过以下两个语句来设置相应的超时: 
System.setProperty("sun.net.client.defaultConnectTimeout", 超时毫秒数字符串); 
System.setProperty("sun.net.client.defaultReadTimeout", 超时毫秒数字符串); 
其中: sun.net.client.defaultConnectTimeout:连接主机的超时时间(单位:毫秒) 
sun.net.client.defaultReadTimeout:从主机读取数据的超时时间(单位:毫秒) 
例如: 
System.setProperty("sun.net.client.defaultConnectTimeout", "30000"); 
System.setProperty("sun.net.client.defaultReadTimeout", "30000"); 
JDK 1.5以前的版本,只能通过设置这两个系统属性来控制网络超时。在1.5中,还可以使用HttpURLConnection的父类URLConnection的以下两个方法: 
setConnectTimeout:设置连接主机超时(单位:毫秒) 
setReadTimeout:设置从主机读取数据超时(单位:毫秒) 
例如: 
HttpURLConnection urlCon = (HttpURLConnection)url.openConnection(); 
urlCon.setConnectTimeout(30000); 
urlCon.setReadTimeout(30000); 
需要注意的是,笔者在JDK1.4.2环境下,发现在设置了defaultReadTimeout的情况下,如果发生网络超时,HttpURLConnection会自动重新提交一次请求,出现一次请求调用,请求服务器两次的问题(Trouble
原创粉丝点击