java.net.SocketException:android模拟器中的协议不支持的地址族

时间:2012-01-11 12:00:04

标签: java android eclipse networking proxy

我正在尝试运行简单的应用程序来从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 server:port -dns-server server

  2. 我在清单文件中包含了互联网权限

    uses-permission android:name =“android.permission.INTERNET”

    uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" 
    
  3. 设置系统属性以在有人建议

    后使用ipv4堆栈
            java.lang.System.setProperty("java.net.preferIPv4Stack", "true");
    java.lang.System.setProperty("java.net.preferIPv6Addresses", "false");
    
  4. 我正在使用Android 2.2和Windows Vista,请你帮我这个......

4 个答案:

答案 0 :(得分:0)

试着做.....

connection.setConnectTimeout(timeoutInMillisecs);

可能你没有设置它。

答案 1 :(得分:0)

尝试将此添加到AndroidManifest.xml中:

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

您还需要捕获此异常:

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

答案 2 :(得分:0)

尝试以编程方式在Oncreate()中设置代理和端口

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

答案 3 :(得分:0)

请试试这个:

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