java如何连网络
Java 连接网络的方法
Java 提供了多种方式连接网络,主要依赖于 java.net 包中的类。以下是几种常见的实现方法。
使用 URL 和 URLConnection
URL 类用于表示统一资源定位符,URLConnection 用于建立与指定 URL 的连接。
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class URLExample {
public static void main(String[] args) throws Exception {
URL url = new URL("https://example.com");
URLConnection connection = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
}
}
使用 HttpURLConnection
HttpURLConnection 是 URLConnection 的子类,专门用于 HTTP 协议。
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpURLExample {
public static void main(String[] args) throws Exception {
URL url = new URL("https://example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
}
}
使用 Socket 编程
Socket 类用于建立客户端与服务器之间的连接。
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class SocketExample {
public static void main(String[] args) throws Exception {
Socket socket = new Socket("example.com", 80);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.println("GET / HTTP/1.1");
out.println("Host: example.com");
out.println();
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
socket.close();
}
}
使用第三方库(如 Apache HttpClient)
Apache HttpClient 是一个功能更丰富的 HTTP 客户端库。

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
public class HttpClientExample {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("https://example.com");
HttpResponse response = client.execute(request);
String result = EntityUtils.toString(response.getEntity());
System.out.println(result);
}
}
注意事项
- 确保网络权限已配置,如在 Android 中需要添加网络权限。
- 处理网络请求时需考虑异常情况,如超时或连接失败。
- 使用 HTTPS 时需注意证书验证问题。
以上方法涵盖了从基础到高级的网络连接需求,可根据具体场景选择适合的方式。






