Java在Debian上的网络设置指南
一、总体思路
二、系统网络先行配置
ip addr(或 ifconfig,旧版工具)auto eth0
iface eth0 inet dhcp
auto eth0
iface eth0 inet static
address 192.168.1.100
netmask 255.255.255.0
gateway 192.168.1.1
dns-nameservers 8.8.8.8 8.8.4.4
sudo systemctl restart networkingnmcli con mod "ens160" ipv4.addresses 192.168.125.137/24
nmcli con mod "ens160" ipv4.gateway 192.168.125.2
nmcli con mod "ens160" ipv4.dns "8.8.8.8 8.8.4.4"
nmcli con mod "ens160" ipv4.method manual
nmcli con up "ens160"
nameserver 8.8.8.8
nameserver 8.8.4.4
ping www.google.comnslookup www.google.com 或 dig www.google.comsudo netplan apply 生效(若你的系统存在该目录与 YAML 文件,请按其语法编辑)。三、Java侧网络参数设置
java -Dhttp.proxyHost=proxy.example.com \
-Dhttp.proxyPort=8080 \
-Dhttps.proxyHost=proxy.example.com \
-Dhttps.proxyPort=8080 \
-Dhttp.nonProxyHosts="localhost|127.0.0.1|*.example.com" \
YourApp
System.setProperty("http.proxyHost", "proxy.example.com");
System.setProperty("http.proxyPort", "8080");
System.setProperty("https.proxyHost", "proxy.example.com");
System.setProperty("https.proxyPort", "8080");
System.setProperty("http.nonProxyHosts", "localhost|127.0.0.1|*.example.com");
-Dsocket.connect.timeout=5000
-Dread.timeout=15000
-Dhttp.maxConnections=200
-Dnetworkaddress.cache.ttl=60
-Dnetworkaddress.cache.negative.ttl=10
四、快速验证与排错
ip addr、ip routeping、nslookup/digimport java.net.*;
import java.io.*;
public class TCPConnection {
public static void main(String[] args) throws IOException {
try (Socket s = new Socket("example.com", 80);
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()))) {
out.println("GET / HTTP/1.1");
out.println("Host: example.com");
out.println();
String l;
while ((l = in.readLine()) != null) System.out.println(l);
}
}
}
import java.net.*;
public class UDPClient {
public static void main(String[] args) throws IOException {
try (DatagramSocket ds = new DatagramSocket()) {
ds.connect(new InetSocketAddress("example.com", 12345));
ds.send(new byte[]{0,0,0,1,72,101,108,108,111,32,87,111,114,108,100});
byte[] buf = new byte[1024];
DatagramPacket p = new DatagramPacket(buf, buf.length);
ds.receive(p);
System.out.println(new String(p.getData(), 0, p.getLength()));
}
}
}
http.nonProxyHosts 未误拦截目标地址;若域名不通,优先排查 DNS 与 路由/防火墙。