采用HTTPClient通过代理连接服务器

本文介绍如何在Java中配置HTTP代理连接,包括全局设置代理、特定连接代理、排除本地主机代理及处理需要认证的代理服务器的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用代理一般的办法是用HTTPConnection的静态方法setProxyServer实现:

  HTTPConnection.setProxyServer("my.proxy.dom", 8008);

  调用该方法以后产生的HTTPConnection对象都会通过该代理建立服务器连接。

  特定某一个连接使用代理:

  setCurrentProxy()

  你也能设置连接某些服务器不要采用代理:

  HTTPConnection.dontProxyFor("localhost");

  如果代理服务器需求用户名密码认证:

  AuthorizationInfo.addDigestAuthorization(host, proxyPort, "", name, pass);

  其中第三个参数是认证域,一般代理服务器能设为空字符串,除非你知道服务器的确切域。

  更有另外一个方法就是使用DefaultAuthHandler:

  DefaultAuthHandler.setAuthorizationPrompter(new MyAuthPrompter(pa_name, pa_pass));

  MyAuthPrompter是实现了AuthorizationPrompter接口的自定义类:

  class MyAuthPrompter implements AuthorizationPrompter

  {

  private String

  pa_name, pa_pass;

  private boolean been_here = false;

  MyAuthPrompter(String pa_name, String pa_pass) {

  this.pa_name = pa_name;

  this.pa_pass = pa_pass;

  }

  public NVPair getUsernamePassword(AuthorizationInfo challenge, boolean forProxy) {

  if (forProxy

  &&

  pa_name != null){

  if (been_here) {

  System.out.println("Proxy authorization failed");

  return null;

  }

  been_here = true;

  return new NVPair(pa_name, pa_pass);

  }

  if (been_here)

  {

  System.out.println("Proxy authorization succeeded");

  }

  // print out all challenge info

  if (forProxy)

  System.out.println("The proxy requires authorization");

  else

  System.out.println("The server requires authorization for this resource");

  return null;

  }

  }

  关于页面认证

  一个页面是否需要认证,及需求认证的信息能通过HTTPClient/doc/GetAuthInfo.java来获取:

  java GetAuthInfo http://some.host.dom/the/file.html

  程式会输出认证信息包括认证域。

  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值