eclipse java.net.SocketException:Android仿真器中的协议不支持地址族

thigvfpy  于 2022-11-04  发布在  Eclipse
关注(0)|答案(4)|浏览(149)

我正在尝试运行简单的应用程序从Android模拟器访问互联网,这里是我的代码。我背后的代理和配置代理设置在模拟器中的”...无线网络-〉APN -〉...”。但互联网是从浏览器工作,而不是从应用程序。

HttpURLConnection connection = null;
    String URLName = "http://www.google.com";

    try {
        URL u = new URL(URLName);
        connection = (HttpURLConnection) u.openConnection();
        connection.setRequestMethod("HEAD");
        int code = connection.getResponseCode();
        Log.d(TAG1, " " + code);
        // You can determine on HTTP return code received. 200 is success.
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Log.d(TAG1, e.toString());
    }

    finally {
        if (connection != null) {
            connection.disconnect();
        }
    }

Logcat中的错误日志部分如下:

01-11 01:01:26.308: DEBUG/SntpClient(72): request time failed: java.net.SocketException: Address family not supported by protocol

01-11 01:02:39.909: WARN/System.err(422): java.net.SocketException: The operation timed out

我在论坛中搜索后尝试了以下选项,但似乎都不起作用:
1.在android启动选项中,我使用了-http-proxy服务器:端口-dns-server服务器
1.我已在清单文件中包括Internet权限
用户权限android:名称=“android.权限.INTERNET”

uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"

1.将系统属性设置为使用ipv4堆栈后有人建议

java.lang.System.setProperty("java.net.preferIPv4Stack", "true");
java.lang.System.setProperty("java.net.preferIPv6Addresses", "false");

我在Android 2.2和Windows Vista的工作,你能请帮助我这里...

laik7k3q

laik7k3q1#

只是试着做.....

connection.setConnectTimeout(timeoutInMillisecs);

可能你没有设置它。

e5nqia27

e5nqia272#

请尝试将以下内容也添加到您的AndroidManifest.xml:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

您还需要捕获此Exception:

catch(SocketException ex)
       {
         Log.e("Error : " , "Error on soapPrimitiveData() " + ex.getMessage());
           ex.printStackTrace();
       }
8hhllhi2

8hhllhi23#

尝试在Oncreate()中以编程方式设置代理和端口,如下所示

System.setProperty("http.proxyHost","IPaddress of ur machine");
      System.setProperty("http.proxyPort","port no");
ux6nzvsh

ux6nzvsh4#

请尝试以下操作:

HttpURLConnection con =null;

URL url = new URL("abcdefg");

Proxy proxy=new Proxy(java.net.Proxy.Type.HTTP, new InetSocketAddress(android.net.Proxy.getDefaultHost(),android.net.Proxy.getDefaultPort()));

con = (HttpURLConnection) url.openConnection(proxy);

相关问题