java.net.SocketException: Address family not suppo

2019-06-22 01:50发布

问题:

I am trying to run simple application to access internet from android emulator and here is my code. I am behind proxy and configured proxy settings in emulator by"...Wireless Networks -> APN -> ..." . But internet is working from browser and not from application.

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

The part of error log in Logcat is as follows:

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

I tried the following options after searching in forum but none of them seems working:

  1. In android launch options I used -http-proxy server:port -dns-server server

  2. I have included internet permissions in manifest file

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

    uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" 
    
  3. Set the system properties to use ipv4 stack after someone suggested

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

I am working on Android 2.2 and windows vista, can you please help me here...

回答1:

Just try to do.....

connection.setConnectTimeout(timeoutInMillisecs);

Probably you r not setting it.



回答2:

Try adding this to your AndroidManifest.xml as well:

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

You also need to catch this Exception:

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


回答3:

Try to set your proxy and port programmatically in Oncreate() like this

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


回答4:

Please try this:

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