Android没有代理无法正常工作?

时间:2012-07-16 06:51:52

标签: android proxy httpurlconnection

我需要在我的应用程序中设置无代理的条件;因为我使用了以下代码:

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

但我得到网络无法访问异常!!

任何帮助!!

1 个答案:

答案 0 :(得分:5)

如果我不误解您的问题...您想通过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。请注意,上面的代码段可能会遗漏一些错误处理。谢谢;)