一段简单的get web 页面的代码
来源:互联网 发布:java培训机构多少钱 编辑:程序博客网 时间:2024/06/08 17:42
虽然很傻,很土,很初级。但是终于开始接触web领域的东西了。
水很深,但是见识了新东西,有点小开心和不开心。
下面的代码会返回www.google.com页面的内容。测试前可以先用浏览器确定自己能访问到指定的页面
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的子类。
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.
因为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
- 一段简单的get web 页面的代码
- 一段简单的代码
- 一段简单的事件代码
- 一段简单的Delphi代码
- 一段简单的javascript代码
- 一段javascript的页面搜索代码
- 一段代码得到本页面的文件名
- 一段javascript的页面搜索代码
- 一段符合Web标准的flash代码
- 【web】一段创建本地文件夹的代码
- 一段简单的反调试代码
- 一段简单的php分页代码示例
- 一段 简单的 multi-thread 代码
- 一段简单的Linux线程池代码
- 记忆深刻的一段简单代码_winvay
- 一段简单的内存检测代码
- 一段简单的图片裁剪代码
- 一段简单的jquery邮箱验证代码
- 关于PHP命名规则
- JFrame中父类和子类窗口的关闭问题
- 关于串口模块化的思考
- ARM中断处理流程
- iPhone4隐藏功能分享
- 一段简单的get web 页面的代码
- 参数编码 完全解决方案
- Java中float,double为什么会丢失精度。
- 2011-11-18
- 继承
- 在 IIS 6.0 中 启用父路径
- 关于一道“智力题”的探讨
- 百度面试offer,值得纪念的一战
- Cookies揭秘 [Asp.Net, Javascript]