Java 使用PreferIPv6地址时的SocketException
因此,我有一个要求,即我需要访问一个URL,而如果它可用,我会选择Java 使用PreferIPv6地址时的SocketException,java,http,httpurlconnection,ipv6,Java,Http,Httpurlconnection,Ipv6,因此,我有一个要求,即我需要访问一个URL,而如果它可用,我会选择IPV6 这是我的一段代码 private HttpURLConnection getConnection(URL url) throws IOException { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setConnectTimeout(15 * 10
IPV6
这是我的一段代码
private HttpURLConnection getConnection(URL url) throws IOException {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setConnectTimeout(15 * 1000);
conn.setRequestMethod("GET");
conn.setRequestProperty("User-Agent", "Mozilla/4.76");
conn.setUseCaches(false);
return conn;
}
我通过缓冲读取器读取连接输出
HttpURLConnection conn = getConnection(new URL(API + urlParameters));
return new BufferedReader(new InputStreamReader(conn.getInputStream())).readLine();
问题发生在引发错误的BufferedReader上
net.SocketException:无法访问网络:连接
但是,当我从应用程序中删除此代码块时,程序将按预期工作。
System.setProperty(“java.net.preferipv6address”,“true”)代码>
但是当然,它发送IPv4
IP地址,即使用户可以使用IPv6
我如何使它发送IPv6
IP如果用户不能使用IPv6
它将使用IPv4
,我正在使用cloudflare记录IP,默认情况下,cloudflare需要从浏览器中获取IPv6。在执行以下操作之前使用此代码测试IPv6支持:
private static boolean supportsIPv6() throws SocketException {
Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
while (e.hasMoreElements()) {
Iterator<InterfaceAddress> e2 = e.nextElement().getInterfaceAddresses().iterator();
while (e2.hasNext()) {
final InetAddress ip = e2.next().getAddress();
if (ip.isLoopbackAddress() || ip instanceof Inet4Address){
continue;
}
return true;
}
}
return false;
}
private静态布尔支持SIPV6()抛出SocketException{
枚举e=NetworkInterface.getNetworkInterfaces();
而(e.hasMoreElements()){
迭代器e2=e.nextElement().getInterfaceAddresses().Iterator();
while(e2.hasNext()){
最终InetAddress ip=e2.next().getAddress();
if(ip.isLoopbackAddress()| | Inet4Address的ip实例){
继续;
}
返回true;
}
}
返回false;
}
在执行以下操作之前,请使用此代码测试IPv6支持:
private static boolean supportsIPv6() throws SocketException {
Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
while (e.hasMoreElements()) {
Iterator<InterfaceAddress> e2 = e.nextElement().getInterfaceAddresses().iterator();
while (e2.hasNext()) {
final InetAddress ip = e2.next().getAddress();
if (ip.isLoopbackAddress() || ip instanceof Inet4Address){
continue;
}
return true;
}
}
return false;
}
private静态布尔支持SIPV6()抛出SocketException{
枚举e=NetworkInterface.getNetworkInterfaces();
而(e.hasMoreElements()){
迭代器e2=e.nextElement().getInterfaceAddresses().Iterator();
while(e2.hasNext()){
最终InetAddress ip=e2.next().getAddress();
if(ip.isLoopbackAddress()| | Inet4Address的ip实例){
继续;
}
返回true;
}
}
返回false;
}
先测试网络:先测试网络: