URL
一个URL,一般来说由2部分组成:
protocol eg http , ftp
resourcename eg www.google.com.hk
而resourcename由4部分组成
hostname eg www.google.com.hk
filename eg /path/file , 是文件在server上的路径
port eg 连接的端口
reference 用来标识file的
而一般来说hostname 和filename会被 使用,而port 和reference不太使用
创建:
1. 直接: URL googleHK = new URL(http://www.google.com.hk );
2. 使用BaseURL URL googleHKmap = new URL(googleHK, “/map”);
如果前面的baseURL为空,则默认后面的为完全的URL
3. 分开各个部分:
new URL(“http”,”www.google.com.hk”,”/map.html”);
4.如果有特殊字符,则需转义,如空格
定义时: new URL(“www.google.com/hello%20world / ”)
也可以定义成 URI ,这时java会为你转化
new URI (“http”,”www.google.com”,”/hello world/”);
URL解析方法:
getProtocol
Returns the protocol identifier component of the URL.
getAuthority
Returns the authority component of the URL.
getHost
Returns the host name component of the URL.
getPort
Returns the port number component of the URL. The getPort method returns an integer that is the port number. If the port is not set, getPort returns -1.
getPath
Returns the path component of this URL.
getQuery
Returns the query component of this URL.
getFile
Returns the filename component of the URL. The getFile method returns the same as getPath, plus the concatenation of the value of getQuery, if any.
getRef
Returns the reference component of the URL.
直接从URL读取内容
URL yahoo = new URL(“http://www.yahoo.com ”);
BufferedReader reader = new BufferedReader(new InputStreamReader(yahoo.openStream()));
String inputLine;
While((inputLine = reader.readLine()) != null){
System.out.println(inputLine);
}
reader.close();
打开URLConnection,进行read , write
import java.net.*;
import java.io.*;
public class URLConnectionReader
{
public static void main(String[] args) throws Exception {
URL yahoo = new URL("http://www.yahoo.com/");
URLConnection yc = yahoo.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
yc.getInputStream()
));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
public class Reverse {
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.err.println("Usage: java Reverse " +
"http://<location of your servlet/script>" +
" string_to_reverse");
System.exit(1);
}
String stringToReverse = URLEncoder.encode(args[1], "UTF-8");
URL url = new URL(args[0]);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(
connection.getOutputStream());
out.write("string=" + stringToReverse);
out.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
String decodedString;
while ((decodedString = in.readLine()) != null) {
System.out.println(decodedString);
}
in.close();
}
}