⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 urlconnectiondemo.java

📁 java程序设计教程的源码
💻 JAVA
字号:
/*【例11-3】  调用URL对象的openConnection()方法创建URLConnection对象,
 * 实现与服务器的数据发送与接收。
 */
//程序清单11-3:  URLConnectionDemo.java
package url;

import java.net.*;
import java.io.*;
import java.util.Date;

public class URLConnectionDemo {
	public static void main(String[] args) throws MalformedURLException,
			IOException {
		// 建立指向网络中cgi的URL对象
		URL url = new URL("http://localhost/ch11/test.cgi");
		// 使用url对象的openConnection()方法,来获取URLConnection类的对象
		URLConnection urlConn = url.openConnection();
		// 使用urlConn对象的getContentType()方法获取资源文件的类型,并显示
		System.out.println("ContentType: " + urlConn.getContentType());
		// 使用urlConn对象的getContentLength()方法获取资源文件的长度
		System.out.println("ContentLength: " + urlConn.getContentLength());
		// 使用urlConn对象的getDate()方法获取资源文件创建的时间
		System.out.println("Date: " + new Date(urlConn.getDate()));
		// 使用urlConn对象的getLastModified()方法获取资源文件最后一次被修改的时间
		System.out.println("LastModified: "
				+ new Date(urlConn.getLastModified()));
		// 向服务器输出数据
		urlConn.setDoOutput(true);
		PrintStream outps = new PrintStream(urlConn.getOutputStream());
		outps.println("ABCDEFGHIJKL");
		outps.close();
		// 从服务器读取数据
		DataInputStream indis = new DataInputStream(urlConn.getInputStream());
		String inputLine;
		while ((inputLine = indis.readLine()) != null) {
			System.out.println(inputLine);
		}
		indis.close();
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -