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();
}
}
}