URI:统计资源标示。
URL :统计资源定位符
笼统地说,每个 URL 都是 URI,但不一定每个 URI 都是 URL。这是因为 URI 还包括一个子类,即统一资源名称 (URN),它命名资源但不指定如何定位资源。
1. Converting Between a URL and a URI URI与URL之间的转化
2. Parsing a URL 解析一个url
3. Sending a POST Request Using a URL
URL :统计资源定位符
笼统地说,每个 URL 都是 URI,但不一定每个 URI 都是 URL。这是因为 URI 还包括一个子类,即统一资源名称 (URN),它命名资源但不指定如何定位资源。
1. Converting Between a URL and a URI URI与URL之间的转化
URI uri = null;
URL url = null;
uri = new URI("file://F:/test.xml");
// Convert a URI to a URL
url = uri.toURL();
// Convert a URL to a URI
uri =url.toURI();
2. Parsing a URL 解析一个url
url = new URL("http://localhost:8080/pplive.htm#ppstream");
String protocol = url.getProtocol(); //http
String host = url.getHost(); //localhost
int port = url.getPort(); //8080
String file = url.getFile(); // /pplive
String ref = url.getRef(); //ppstream
3. Sending a POST Request Using a URL
Client:
String data = URLEncoder.encode("key1","UTF-8")+"="+URLEncoder.encode("value1","UTF-8");
data += "&"+URLEncoder.encode("key2","UTF-8")+"="+URLEncoder.encode("value2","UTF-8");
System.out.println(data);
URL url = new URL("http://127.0.0.1:56231/test/test/"); //切忌不要把应用名称给忘记了
URLConnection con = url.openConnection();
//send data
con.setDoOutput(true);
con.setDoInput(true);
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
writer.write(data);
writer.flush();
//get response
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = null;
while((line = br.readLine()) != null){
System.out.println(line);
}
writer.close();
br.close();
Service:
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream())); //这个例子还是有点问题的
String line = null;
StringBuilder sb = new StringBuilder();
while((line = br.readLine()) != null){
sb.append(line);
}
System.out.println(sb.toString());
PrintWriter pw = new PrintWriter(response.getOutputStream(),true);
String data = "i'am back !";
pw.write(data);
pw.flush();
pw.close();
br.close();