Java網路程式設計之使用URL類
Lesson: Working with URLs 使用URLs
整理自Oracle官方文件。
URL is the acronym for Uniform Resource Locator.
URL是Uniform Resource Locator的縮寫
It is a reference (an address) to a resource on the Internet.
它是一個網路資源的引用(地址)
You provide URLs to your favorite Web browser so that it can locate files on the Internet in the same way that you provide addresses on letters so that the post office can locate your correspondents.
Java programs that interact with the Internet also may use URLs to find the resources on the Internet they wish to access. Java programs can use a class called URL in the java.net package to represent a URL address.
Java程式提供URL類來實現URL地址
Terminology Note:
The term URL can be ambiguous. It can refer to an Internet address or a URL object in a Java program. Where the meaning of URL needs to be specific, this text uses "URL address" to mean an Internet address and "URL object" to refer to an instance of the URL class in a program.
What Is a URL? 什麼是URL
A URL takes the form of a string that describes how to find a resource on the Internet. URLs have two main components: the protocol needed to access the resource and the location of the resource.
Creating a URL 建立URL
Within your Java programs, you can create a URL object that represents a URL address. The URL object always refers to an absolute URL but can be constructed from an absolute URL, a relative URL, or from URL components.
Parsing a URL 解析URL
Gone are the days of parsing a URL to find out the host name, filename, and other information. With a valid URL object you can call any of its accessor methods to get all of that information from the URL without doing any string parsing!
Reading Directly from a URL讀取URL資料
This section shows how your Java programs can read from a URL using the openStream() method.
import java.net.*;
import java.io.*;
public class URLReader {
public static void main(String[] args) throws Exception {
URL oracle = new URL("http://www.oracle.com/");
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
Connecting to a URL連線URL
If you want to do more than just read from a URL, you can connect to it by calling openConnection() on the URL. The openConnection() method returns a URLConnection object that you can use for more general communications with the URL, such as reading from it, writing to it, or querying it for content and other information.
try {
URL myURL = new URL("http://example.com/");
URLConnection myURLConnection = myURL.openConnection();
myURLConnection.connect();
}
catch (MalformedURLException e) {
// new URL() failed
// ...
}
catch (IOException e) {
// openConnection() failed
// ...
}
Reading from and Writing to a URLConnection
向一個URLConnection讀寫資料
Some URLs, such as many that are connected to cgi-bin scripts, allow you to (or even require you to) write information to the URL. For example, a search script may require detailed query data to be written to the URL before the search can be performed. This section shows you how to write to a URL and how to get results back.
import java.net.*;
import java.io.*;
public class URLConnectionReader {
public static void main(String[] args) throws Exception {
URL oracle = new URL("http://www.oracle.com/");
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
Post data to a URL 向一個URL提交資料步驟
1. Create a URL.
2. Retrieve the URLConnection object.
3. Set output capability on the URLConnection.
4. Open a connection to the resource.
5. Get an output stream from the connection.
6. Write to the output stream.
7. Close the output stream.
Reverse.java
package com.dylan.net;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
/**向伺服器傳送需要進行倒序排序的字串
* @author xusucheng
* @create 2017-12-23
**/
public class Reverse {
public static void main(String[] args) throws Exception{
String[] arr = {"http://localhost:8080/helloweb/ReverseServlet","eM esreverR"};
if(arr.length !=2){
System.err.println("Usage: java Reverse "
+ "http://<location of your servlet/script>"
+ " string_to_reverse");
System.exit(1);
}
String stringToReverse = URLEncoder.encode(arr[1],"UTF-8");
URL url = new URL(arr[0]);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
//拿到輸出流,向伺服器傳送資訊
PrintWriter out = new PrintWriter(connection.getOutputStream());
out.write("string=" + stringToReverse);
out.flush();
out.close();
//拿到輸入流,讀取服務端發回資訊
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String decodeString;
while ((decodeString=in.readLine())!=null){
System.out.println(decodeString);
}
in.close();
}
}
ReverseServlet.java
package servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.URLDecoder;
@WebServlet(name = "ReverseServlet", urlPatterns = "/ReverseServlet")
public class ReverseServlet extends HttpServlet {
private static String message = "Error during Servlet processing";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
int len = request.getContentLength();
if (len < 0) {
response.setContentType("text/html;charset=utf-8");
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.getWriter().print("請求方式錯誤!");
response.getWriter().close();
return;
}
byte[] input = new byte[len];
ServletInputStream sin = request.getInputStream();
int c, count = 0;
while ((c = sin.read(input, count, input.length - count)) != -1) {
count += c;
}
sin.close();
String inString = new String(input);
int index = inString.indexOf("=");
if (index == -1) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.getWriter().print(message);
response.getWriter().close();
return;
}
String value = inString.substring(index + 1);
//decode application/x-www-form-urlencoded string
String decodedString = URLDecoder.decode(value, "UTF-8");
//reverse the String
String reverseStr = (new StringBuffer(decodedString)).reverse().toString();
// set the response code and write the response data
response.setStatus(HttpServletResponse.SC_OK);
OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream());
writer.write(reverseStr);
writer.flush();
writer.close();
} catch (IOException e) {
try {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.getWriter().print(e.getMessage());
response.getWriter().close();
} catch (IOException ioe) {
}
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
相關文章
- java程式設計之:Unsafe類Java程式設計
- Java網路程式設計之UDPJava程式設計UDP
- URL程式設計程式設計
- JAVA實現網路程式設計之併發程式設計Java程式設計
- 好程式設計師Java教程分享Java之包裝類與常用類程式設計師Java
- 另類網路層設計
- java併發程式設計:Thread類的使用Java程式設計thread
- 好程式設計師Java學習路線分享MyBatis之基本使用程式設計師JavaMyBatis
- 3.Java網路程式設計之IPJava程式設計
- RestFul Api 設計 之 URLRESTAPI
- Java的網路功能與程式設計 一 (轉)Java程式設計
- Java中神經網路Triton GPU程式設計Java神經網路GPU程式設計
- python網路-Socket之TCP程式設計(26)PythonTCP程式設計
- 黑馬程式設計師——Java學習筆記之⑦——“網路程式設計”程式設計師Java筆記
- 好程式設計師Java學習路線之集程式設計師Java
- Java併發程式設計之CyclicBarrier使用指南Java程式設計
- Java 網路程式設計Java程式設計
- JAVA網路程式設計Java程式設計
- JAVA網路程式設計(2)TCP程式設計Java程式設計TCP
- Java併發程式設計:Thread類的使用介紹Java程式設計thread
- Java程式設計思想學習錄(連載之:內部類)Java程式設計
- Java 網路程式設計(TCP程式設計 和 UDP程式設計)Java程式設計TCPUDP
- Java網路程式設計之SocketChannel和ServerSocketChannelJava程式設計Server
- 好程式設計師Java教程分享Java之設計模式程式設計師Java設計模式
- Java 網路程式設計 —— 非阻塞式程式設計Java程式設計
- 網路通訊程式設計程式設計
- 網路協程程式設計程式設計
- Socket 程式設計 (網路篇)程式設計
- py網路工具程式設計程式設計
- mapreduce 程式設計SequenceFile類的使用程式設計
- Java設計模式-類之間的關係Java設計模式
- 好程式設計師Java學習路線分享Java案例-封裝JDBC工具類程式設計師Java封裝JDBC
- 好程式設計師Java學習路線之SpringMVC之基本配置程式設計師JavaSpringMVC
- 程式設計師必看的書之Java程式設計師程式設計師Java
- 程式設計師之間的十八層鄙視網路程式設計師
- java 網路程式設計01Java程式設計
- Java網路程式設計初探Java程式設計
- Java網路程式設計(一)Java程式設計