HttpURLConnection是java的标准类,HttpURLConnection继承自URLConnection,可用于向指定网站发送GET请求、POST请求。它在URLConnection的基础上提供了如下便捷的方法:
• int getResponseCode():获取服务器的响应代码。
• String getResponseMessage():获取服务器的响应消息。
• String getResponseMethod():获取发送请求的方法。
• void setRequestMethod(String method):设置发送请求的方法。
在一般情况下,如果只是需要Web站点的某个简单页面提交请求并获取服务器响应,HttpURLConnection完全可以胜任。但在绝大部分情况下,Web站点的网页可能没这么简单,这些页面并不是通过一个简单的URL就可访问的,可能需要用户登录而且具有相应的权限才可访问该页面。在这种情况下,就需要涉及Session、Cookie的处理了,如果打算使用HttpURLConnection来处理这些细节,当然也是可能实现的,只是处理起来难度就大了。 public static int getCode(String httpurl)
{
URL url;
int responsecode = 0;
HttpURLConnection urlConnection;
try{
//生成一个URL对象,要获取源代码的网页地址为:http://www.sina.com.cn
url=new URL("http://"+httpurl);
//打开URL
urlConnection = (HttpURLConnection)url.openConnection();
//获取服务器响应代码
responsecode=urlConnection.getResponseCode();
urlConnection.setConnectTimeout(3000);
urlConnection.setReadTimeout(3000);
//等待3秒--如果不行就下一个---不能超时
/* int maxCount = 2;
int currentCount = 0;
while(currentCount < maxCount){
int code = responsecode;
if (code!= 200){ // 请求不成功
System.out.println("---111---");
currentCount++;
System.out.println("---currentCount---"+currentCount);
Thread.sleep(3000);// 等待3s
}
}*/
if(responsecode==200){
System.out.println("httpurl==>"+httpurl);
}
else{
System.out.println("获取不到网页的源码,服务器响应代码为:"+responsecode);
}
}
catch(Exception e){
System.out.println("获取不到网页的源码,出现异常:"+e);
}
return responsecode;
}
}