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

    技术2022-05-11  115

    使用代理一般的办法是用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

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

     

    附注:

    下载要求用户认证的页面时, HTTPClient 会弹出用户名密码以及作用域输入框。假如需要取消输入弹出对话框的话,可以调用 HTTPConnection setAllowUserInteraction(false) 方法。

    最新回复(0)