服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

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


  使用代理一般的办法是用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
  
  程序会输出认证信息包括认证域。

扫描关注微信公众号