Java 網路程式設計常用協定與函式庫:協定:TCP、UDP、HTTP、HTTPS、FTP函式庫:java.net、java.nio、Apache HttpClient、Netty、OkHttp

#Java 網路編程中的常用協定和函式庫
Java 提供了豐富的函式庫和框架來簡化網路編程,以下列出了一些常用的協定和函式庫:
協議
庫
實戰案例
傳送HTTP GET 請求
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpGetExample {
public static void main(String[] args) throws Exception {
String url = "https://www.example.com";
// 创建 HttpURLConnection
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求方法和内容类型
con.setRequestMethod("GET");
con.setRequestProperty("Content-Type", "application/json");
// 发送请求并获取响应代码
int responseCode = con.getResponseCode();
// 打印响应正文
System.out.println("Response Code: " + responseCode);
Scanner scanner = new Scanner(con.getInputStream());
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
}
}建立TCP 伺服器
#import java.net.ServerSocket;
import java.net.Socket;
public class TcpServerExample {
public static void main(String[] args) throws Exception {
// 监听端口
int port = 8080;
// 创建 ServerSocket
ServerSocket serverSocket = new ServerSocket(port);
// 循环等待客户端连接
while (true) {
// 接受客户端连接
Socket clientSocket = serverSocket.accept();
// 创建新线程处理客户端连接
Thread thread = new Thread(() -> {
try {
// 获取客户端输入流
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
// 打印客户端发来的数据
String line;
while ((line = in.readLine()) != null) {
System.out.println("Message from client: " + line);
}
} catch (Exception e) {
e.printStackTrace();
}
});
thread.start();
}
}
}以上是Java 網路程式設計中常用的協定和函式庫有哪些?的詳細內容。更多資訊請關注PHP中文網其他相關文章!