/*
String getFile();获取此URL的文件名
String getHost();获取此URL的主机名
String getPath();获取此URL的路径部分
int getPort();获取此URL的端口号
String getProtocol();获取此URL的协议名称
String getQuery();获取此URL的查询部分
*/
import java.net.*;
class URLDemo {
public static void main(String[] args) throws{
URL url = new URL("http://192.168.1.254:8080/myweb/1.html?name=haha&age=30");
System.out.println("getFile():"+url.getFile());// /myweb/1.html
System.out.println("getHost():"+url.getHost());// 192.168.1.254
System.out.println("getPath():"+url.getPath());// /myweb/1.html
System.out.println("getPort():"+url.getPort());// 8080 不指定端口返回-1
System.out.println("getProtocol():"+url.getProtocol());// http
System.out.println("getQuery():"+url.getQuery());// name=haha&age=30
/*
int port = getPort();
if(port == -1)
port = 80;
*/
}
}
/*------------------------------------------------------------------------*/
//URLConnection
import java.net.*;
import java.io.*;
class URLConnectionDemo{
public static void main(String[] args)throws Exception{
URL url = new URL("http://www.baidu.com");
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
byte[] buffer = new byte[1024];
int len = is.read(buffer);
System.out.println(new String(buffer,0,len));
}
}
网络编程--URL,URLConnection
最新推荐文章于 2023-04-12 20:38:48 发布