📄 urlconnectionsample.java
字号:
//URLConnection.java
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
public class URLConnectionSample {
public static void main(String[] args) {
//只接受一个命令行参数,这个参数作为URL使用
if (1 != args.length) {
System.err.println("Usage: java URLConnectionSample url");
return;
}
try {
//读取命令行参数,将第一个参数解释为URL
URL url = new URL(args[0]);
// 通过URL对象构造URLConnection对象
URLConnection con = url.openConnection();
//连接到URL
con.connect();
//输出相关的信息
System.out.println(" Content Type: " + con.getContentType());
System.out.println(" Content Encoding: " + con.getContentEncoding());
System.out.println(" Content Length: " + con.getContentLength());
System.out.println(" Date: " + new Date(con.getDate()));
System.out.println(" Last Modified: " + new Date(con.getLastModified()));
System.out.println(" Expiration: " + new Date(con.getExpiration()));
//如果URL对象的协议被设置为HTTP协议,
//那么返回的URLConnection对象实际上是一个HttpURLConnection对象
//通过使用HTTPURLConnection对象,可以获得一些与HTTP协议相关的
//信息,如状态码
if (con instanceof HttpURLConnection) {
HttpURLConnection h = (HttpURLConnection) con;
System.out.println(" Request Method: " + h.getRequestMethod());
System.out.println(" Response Message: " + h.getResponseMessage());
//返回服务器发回的状态码,如果状态码不是2xx,那么肯定发生了错误
System.out.println(" Response Code: " + h.getResponseCode());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -