2012-07-16 32 views
6

Necesito la condición de no establecer proxy en mi aplicación; para que utilicé el siguiente código:Android sin proxy no funciona?

URL url = null; 

try { 
    url = new URL(uri.toURL().toString()); 
} catch (MalformedURLException e3) { 
    e3.printStackTrace(); 
} 

try { 
    //client = (HttpURLConnection) url.openConnection(java.net.Proxy.NO_PROXY); 
    Properties systemProperties = System.getProperties(); 

    systemProperties.setProperty("http.nonProxyHosts",ServerIP); 
    systemProperties.setProperty("proxySet", "false"); 
    systemProperties.setProperty("http.proxyHost",""); 
    systemProperties.setProperty("http.proxyPort",""); 
    URLConnection conn = url.openConnection(Proxy.NO_PROXY); 


    conn.connect(); 
} catch (IOException e3) { 
    e3.printStackTrace(); 
} 

Pero tengo red inalcanzable excepción !!

Cualquier ayuda !!

+0

¿Puede dar más detalles sobre su problema? ¿Cuál es el escenario? ¿Falla en el emulador o en un dispositivo? o ambos ? ¿Cuál es tu entorno de red? – fiddler

+0

Hola, mi objetivo es conectarme a un servidor utilizando un entorno proxy y no proxy. Estoy ejecutando la aplicación en el dispositivo Android y la conexión se realiza a través de wifi. – info

Respuesta

5

Si no entiendo mal tu pregunta ... ¿Quieres conectarte directamente al servidor cuando se conecta a través de WIFI?

HttpURLConnection con =null; 
URL url = new URL("xxxxx"); 
boolean isProxy=true; 

ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 
if(cm!=null){ 
    NetworkInfo ni = cm.getActiveNetworkInfo(); 
    if(ni!=null){ 
     if(! ni.getTypeName().equals("WIFI")){ 
      isProxy=false; 
     } 
     if(isProxy){ 
      Proxy proxy=new Proxy(java.net.Proxy.Type.HTTP,new InetSocketAddress(android.net.Proxy.getDefaultHost(),android.net.Proxy.getDefaultPort())); 
      con = (HttpURLConnection) url.openConnection(proxy); 
     }else{ 
      con = (HttpURLConnection) url.openConnection(); 
     } 
    } 
} 

p.s. Tenga en cuenta que el fragmento de código anterior puede omitir el manejo de errores. Gracias;)