Java如何查詢系統的代理設定?

2019-10-16 22:28:10

在Java程式設計中,如何查詢系統的代理設定?

以下範例顯示如何使用HttpURLConnection類的systemSetting()方法和getResponse()方法的put方法在系統上查詢代理設定並建立代理連線。

package com.yiibai;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Properties;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.URI;

public class FindProxySettings{
   public static void main(String s[]) throws Exception {
      try {
         Properties systemSettings = System.getProperties();
         systemSettings.put("proxySet", "true");
         systemSettings.put("http.proxyHost", "proxy.yiibai.local");
         systemSettings.put("http.proxyPort", "80");

         URL u = new URL("http://www.google.com");
         HttpURLConnection con = (HttpURLConnection)u.openConnection();
         System.out.println(con.getResponseCode() + " : " + con.getResponseMessage());
         System.out.println(con.getResponseCode() == HttpURLConnection.HTTP_OK);
      } catch (Exception e) {
         e.printStackTrace();
         System.out.println(false);
      }
      System.setProperty("java.net.useSystemProxies", "true");
      Proxy proxy = (Proxy) ProxySelector.getDefault().select(new URI(
         "http://www.baidu.com/")).iterator().
      next();;
      System.out.println("proxy hostname : " + proxy.type());
      InetSocketAddress addr = (InetSocketAddress)proxy.address();

      if (addr == null) {
         System.out.println("No Proxy");
      } else {
         System.out.println("proxy hostname : " + addr.getHostName());
         System.out.println("proxy port : " + addr.getPort());
      }
   }
}

上述程式碼範例將產生以下結果 -

200 : OK
true
proxy hostname : HTTP
proxy hostname : proxy.yiibai.local
proxy port : 80

範例-2

以下是查詢系統的代理設定的另一個範例:

package com.yiibai;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.URI;
import java.util.Iterator;
import java.util.List;

public class FindProxySettings2 {
    public static void main(String[] args) {
        try {
            System.setProperty("java.net.useSystemProxies", "true");
            List<Proxy> l = ProxySelector.getDefault().select(new URI("http://www.google.com/"));

            for (Iterator<Proxy> iter = l.iterator(); iter.hasNext();) {
                Proxy proxy = iter.next();
                System.out.println("proxy hostname : " + proxy.type());
                InetSocketAddress addr = (InetSocketAddress) proxy.address();

                if (addr == null) {
                    System.out.println("No Proxy");
                } else {
                    System.out.println("proxy hostname : " + addr.getHostName());
                    System.out.println("proxy port : " + addr.getPort());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

上述程式碼範例將產生以下結果 -

proxy hostname : DIRECT
No Proxy