您的位置:首页 > 编程语言

一段简单的get web 页面的代码

2011-11-19 09:54 183 查看
虽然很傻,很土,很初级。但是终于开始接触web领域的东西了。


水很深,但是见识了新东西,有点小开心和不开心。




下面的代码会返回www.google.com页面的内容。测试前可以先用浏览器确定自己能访问到指定的页面



import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.URL;

public class Main {

public static void main(String args[]) throws Exception {

//创建一个URL对象。

URL url = new URL("http://www.google.com");

//url.openConnection()创建一个URLConnection对象。同时这个方法还可以使用指定的代理。HttpURLConnection是URLConnection的子类。

HttpURLConnection httpCon = (HttpURLConnection)url.openConnection();

InputStream inStrm = httpCon.getInputStream();

System.out.println("\nContent at " + url);

int ch;

while (((ch = inStrm.read()) != -1))

System.out.print((char) ch);

inStrm.close();

}

}

下面这个类是重点:

URLConnection:

The abstract class
URLConnection
is the superclass of all classes that represent a communications link between the application and a URL.Instances of this class can be used both to read from and to write to the resource referenced by the URL.

所以这个类会很常用的。基本上访问一个URL的过程是:

The connection object is created by invoking the
openConnection
method on a URL.
The setup parameters and general request properties are manipulated.
The actual connection to the remote object is made, using the
connect
method.
The remote object becomes available. The header fields and the contents of the remote object can be accessed.

但是实际上要简单一些。例如上面的代码中使用openConnection()之后,并没有使用Connet(),而是直接使用了getInputStream()。

因为getInputStream
and
getContent
, which are mirrored in the
URL
class by convenience methods.

另外的类是HttpURLConnection 和 URL。

Each HttpURLConnection instance is used to make a single request but the underlying network connection to the HTTP servermay be transparently shared by other instances. Calling theclose()methods
on the InputStream or OutputStream of an HttpURLConnection after a request may free network resources associated with this instance but has no effect on any shared persistent connection. Calling thedisconnect() method
may close the underlying socket if a persistent connection is otherwise idle at that time.

另外一个类URL更好。在java api中有对URL的简短介绍,URL的组成部分和意义,对我这种一无所知的人很有用。

因此需要重点看的java api是:

URLConnection, URL, HttpURLConnection

同时想恶补一下http和URL知识的,看看下面这个非常好的网站,中文的哟~:
http://www.w3school.com.cn/html/html_url.asp
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: