代码如下,根据输入的url地址来返回状态码。
可是,httpconnection.getResponseCode();返回的都是200,没有实际返回访问值。
请高手指点。
public String stat_is(String strurl)
{
HttpURLConnection httpconnection;
int rcode=0;
String respon = "ok";
httpconnection = null;
//String strurl=siteaddr;
try{
URL url = new URL(strurl);
httpconnection = (HttpURLConnection) url.openConnection();
httpconnection.setConnectTimeout(2*1000);
httpconnection.setRequestMethod("GET");
httpconnection.setDoInput(true);
httpconnection.setRequestProperty("Charset", "UTF-8");
httpconnection.setUseCaches(false);
httpconnection.setRequestProperty("Connection", "Keep-Alive");
//httpconnection.setRequestProperty("Content-type", "application/x-java-serialized-object");
//InputStream input = httpconnection.getInputStream();
//readStream(input);
//httpconnection.setRequestProperty("Content-Type", "application/xhtml+xml");
//mes = httpconnection.getResponseMessage();
httpconnection.connect();
rcode = httpconnection.getResponseCode();
if (rcode == 200){
respon="ok";
}
else
{
respon="error";
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (httpconnection != null) {
httpconnection.disconnect();
}
}
return respon;
}
200 (成功) 表示服务器已成功处理了请求。 通常,这表示服务器提供了请求的网页。
然后,要去读数据流,如下代码:
URL url = new URL("http://www.sohu.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(6* 1000);//设置连接超时
if (conn.getResponseCode() != 200)
throw new RuntimeException("请求url失败");
InputStream is = conn.getInputStream();//得到网络返回的输入流
String result = readData(is, "GBK");
conn.disconnect();
System.out.println(result);
//第一个参数为输入流,第二个参数为字符集编码
public static String readData(InputStream inSream, String charsetName) throws Exception{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while( (len = inSream.read(buffer)) != -1 ){
outStream.write(buffer, 0, len);
}
byte[] data = outStream.toByteArray();
outStream.close();
inSream.close();
return new String(data, charsetName);
}