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

inf*_*nfo 6 proxy android 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();
}
Run Code Online (Sandbox Code Playgroud)

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

任何帮助!!

hun*_*ngr 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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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