java url 访问_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();

}

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


版权声明:本文为weixin_35761245原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。