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

虽然很傻,很土,很初级。但是终于开始接触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的过程是:

  1. The connection object is created by invoking the openConnection method on a URL.
  2. The setup parameters and general request properties are manipulated.
  3. The actual connection to the remote object is made, using the connect method.
  4. 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 theURL 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



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值