java.net--URL

本文详细解释了URI与URL的概念及其区别,并提供了二者互相转换的示例代码。此外,还介绍了如何通过URL进行资源定位及发送POST请求的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

URI:统计资源标示。
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();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值