Java HttpURLConnection 通过代理连接

网络属性

您必须设置以下属性:

http.proxyHost(默认:<none>)
http.proxyPort(默认值:80 如果指定了 http.proxyHost)
http.nonProxyHosts(默认值:<none>)

注意: proxyHostproxyPort已弃用。你必须在它们前面加上“http.”。
注意:这些属性记录在此处: http : //java.sun.com/javase/6/docs/technotes/guides/net/properties.html

您可以在从命令行为 JAVA 应用程序启动 JVM 时设置所需的属性:

java -Dhttp.proxyHost=myproxyserver.com -Dhttp.proxyPort=80 MyJavaApp

或在您的来源:

System.setProperty("http.proxyHost", "myProxyServer.com");
System.setProperty("http.proxyPort", "80");

Java 1.5 开始,您还可以将 java.net.Proxy 实例传递给 openConnection() 方法:

//代理实例,代理ip = 123.0.0.1 8080端口
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("123.0.0.1", 8080));
URL url = new URL("http://www.yahoo.com");
HttpURLConnection uc = (HttpURLConnection)url.openConnection(proxy);
uc.connect();

字符串页面;
StringBuffer tmp = new StringBuffer();
BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
while ((line = in.readLine()) != null){
   page.append(line + "\n");
}
System.out.println(page);

所以你不需要设置系统属性。

您可以使用由您的网络设置定义的默认代理。

System.setProperty("java.net.useSystemProxies", "true");
List l = null;
try {
  l = ProxySelector.getDefault().select(new URI("http://www.yahoo.com"));
}
catch (URISyntaxException e) {
  e.printStackTrace();
}

if (l != null) {
   for (Iterator iter = l.iterator(); iter.hasNext() {
      java.net.Proxy proxy = (java.net.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());
      }
   }
}

要绕过代理,

URL url = new URL("http://internal.server.local/");
URLConnection conn = url.openConnection(Proxy.NO_PROXY);

代理和用户名/密码

您可能需要向代理服务器表明自己的身份。

一种方法是使用带有用户名:密码 base64 编码的 HTTP 属性“代理授权”。

System.setProperty("http.proxyHost", "myProxyServer.com");
System.setProperty("http.proxyPort", "80");
URL url=new URL("http://someserver/somepage");
URLConnection uc = url.openConnection ();
String encoded = new String
      (Base64.base64Encode(new String("username:password").getBytes()));
uc.setRequestProperty("Proxy-Authorization", "Basic " + encoded);
uc.connect();

注意:有关 base64 函数,请参阅此操作方法


以下示例在我们向代理标识自己之前转储 URL 的内容。

import java.net.*;
import java.io.*;

public class URLUtils {
  public static void main(String s[]) {
    URLUtils.dump("http://www.yahoo.com");
    System.out.println("**************");
    URLUtils.dump("https://www.paypal.com");
    System.out.println("**************");
  }

  public static void dump(String URLName){
    try {
      DataInputStream di = null;
      FileOutputStream fo = null;
      byte [] b = new byte[1];

      // PROXY
      System.setProperty("http.proxyHost","proxy.mydomain.local") ;
      System.setProperty("http.proxyPort", "80") ;

      URL u = new URL(URLName);
      HttpURLConnection con = (HttpURLConnection) u.openConnection();
      //
      // it's not the greatest idea to use a sun.misc.* class
      // Sun strongly advises not to use them since they can
      // change or go away in a future release so beware.
      //
      sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
      String encodedUserPwd =
         encoder.encode("mydomain\\MYUSER:MYPASSWORD".getBytes());
      con.setRequestProperty
         ("Proxy-Authorization", "Basic " + encodedUserPwd);
      // PROXY ----------

      di = new DataInputStream(con.getInputStream());
      while(-1 != di.read(b,0,1)) {
         System.out.print(new String(b));
      }
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }
}

使用 JDK1.2, 可以在需要时使用java.net.Authenticator发送凭据。

public static void dump(String URLName){
  try {
    DataInputStream di = null;
    FileOutputStream fo = null;
    byte [] b = new byte[1];

    // PROXY
    System.setProperty("http.proxyHost","proxy.mydomain.local") ;
    System.setProperty("http.proxyPort", "80") ;

    Authenticator.setDefault(new Authenticator() {
      protected PasswordAuthentication getPasswordAuthentication() {
        return new
           PasswordAuthentication("mydomain\\username","password".toCharArray());
    }});

    URL u = new URL(URLName);
    HttpURLConnection con = (HttpURLConnection) u.openConnection();
    di = new DataInputStream(con.getInputStream());
    while(-1 != di.read(b,0,1)) {
       System.out.print(new String(b));
    }
  }
  catch (Exception e) {
          e.printStackTrace();
  }
}

绕过代理

在内网环境下,可能需要绕过代理服务器,直接进入http服务器。

该 http.nonProxyHosts属性表示应该太直接不连接通过代理服务器的主机。该值可以是主机列表,每个主机由 | 分隔,此外还可以使用通配符 (*) 进行匹配。

java.exe
   -Dhttp.nonProxyHosts="*.mycompany.com|*.mycompany.local|localhost"
      MyClass
Java可以通过代理服务器访问其他服务器,可以使用Java提供的java.net包中的Proxy类来实现代理服务器的设置。下面是一个示例代码: ``` import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.URL; public class ProxyExample { public static void main(String[] args) throws Exception { // 设置代理服务器地址和端口号 String proxyHost = "proxy.example.com"; int proxyPort = 8080; // 创建代理服务器对象 Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); // 创建要访问的URL对象 URL url = new URL("http://www.example.com"); // 打开连接并设置代理服务器 HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy); // 设置请求方式和超时时间 connection.setRequestMethod("GET"); connection.setConnectTimeout(5000); // 读取响应内容 BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); // 关闭连接 connection.disconnect(); } } ``` 在这个示例中,我们使用了一个代理服务器地址为"proxy.example.com",端口号为8080。创建代理服务器对象时,我们使用了Proxy类,并指定了代理类型为HTTP。然后将代理服务器对象传递给了URL.openConnection()方法,从而打开了一个连接,并在连接中设置了代理服务器。 最后,我们读取了响应内容,并关闭了连接
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值