三度网教程:是一个免费提供流行视频软件教程、在线学习分享的学习平台!

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

时间:2024/6/10作者:未知来源:三度网教程人气:


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

关键词:  采纳HTTPClient通过代理连接服务器





Copyright © 2012-2018 三度网教程(http://www.3du8.cn) .All Rights Reserved 网站地图 友情链接

免责声明:本站资源均来自互联网收集 如有侵犯到您利益的地方请及时联系管理删除,敬请见谅!

QQ:1006262270   邮箱:kfyvi376850063@126.com   手机版