Java 访问已知的url方法

       在网络编程中,很多时候会遇到给你一个固定的url ,让你去耙一些东西回来,通常有如下三中操作:

      method one :
           URL url = new URL("http://www.baidu.com");
           URLConnection urlcon = url.openConnection();
           InputStream is = urlcon.getInputStream();
          
       method two:
           URL url = new URL("http://www.google.com.hk");
           HttpURLConnection urlcon = (HttpURLConnection)url.openConnection();
           InputStream is = urlcon.getInputStream();
          
       method three:
           URL url = new URL("http://www.sina.com.cn");
           InputStream is = url.openStream();


但是这在三种方法之中,最好实用的是:method two , 因为很多时候我们都是通过http协议来访问浏览器的。直接贴代码看吧:



String urlStr = "www.baidu.com";
URL url;
try {
url = new URL(urlStr);
URLConnection URLconnection = url.openConnection(); // 打开连接
HttpURLConnection httpConnection = (HttpURLConnection) URLconnection; // 类型转换
int responseCode = httpConnection.getResponseCode(); // 判断是什么协议的请求
// HttpURLConnection.
// 可以得到很多的类型
httpConnection.setRequestMethod("POST");

if (responseCode == HttpURLConnection.HTTP_OK) {
System.err.println("连接成功了... ...");
InputStream urlStream = httpConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(urlStream));
String sCurrentLine = "";
String sTotalString = "";
while ((sCurrentLine = bufferedReader.readLine()) != null) {
sTotalString += sCurrentLine;
}
System.err.println(sTotalString);
// 假设该url页面输出为"OK",对内容进行判断
if (sTotalString.equals("OK")) {

urlStream.close();
httpConnection.disconnect();

} else {

}



} else {
System.err.println("失败,不是Http请求... ...");
}
} catch (Exception e) {
// TODO Auto-generated catch blockeb
e.printStackTrace();
}

基本也就是这样的东东了,其他的处理方式和这个是一样的。。。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值