一段简单的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
URLConnectionis 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
openConnectionmethod on a URL.
The setup parameters and general request properties are manipulated.
The actual connection to the remote object is made, using the
connectmethod.
The remote object becomes available. The header fields and the contents of the remote object can be accessed.
但是实际上要简单一些。例如上面的代码中使用openConnection()之后,并没有使用Connet(),而是直接使用了getInputStream()。
因为getInputStreamand
getContent, which are mirrored in the
URLclass 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
相关文章推荐
- 一段简单的使用js在web页面中显示日期时间的代码
- 通过flask实现web页面简单的增删改查
- 一段点击隐藏部分页面的效果代码
- 一段代码实现天气预报在自己页面显示
- 【轻松一刻!】一段难倒了两名老程序猿的简单代码
- 开源的c/c++编译器 mingm 编译、执行一段简单的c/c++代码
- php实现的一段简单概率相关代码
- webView 加载页面的两种请求方式: get 和 post
- loadrunner 一段简单实用的登录代码
- 用一行python代码做一个简单的web服务器
- Spring Web Flow 入门demo(一)简单页面跳转 附源码
- 求一段smartupload上传图片的代码,不需要保存到数据库,但是想在jsp页面选中文件夹图片后,立马可以显示
- 两种Web页面局部刷新技术的简单较量
- Web浏览器中动态添加修改HTML页面代码的问题分析
- webView 显示一段 html 代码
- 《网络渗透技术》学习笔记(2)——一段简单的汇编代码分析 zz
- 一段获取ssdt表及其中函数的简单代码
- php编写的简单页面跳转功能实现代码
- 自动把纯文本转换成Web页面的php代码
- 一段简单的代码告诉你什么叫内存溢出