7

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

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

但是我遇到了网络无法访问的异​​常!!

任何帮助!

4

1 回答 1

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

ps 请注意,上面的代码片段可能会遗漏一些错误处理。谢谢 ;)

于 2012-07-19T04:07:57.450 回答