我必须登录https网页并使用Java下载文件。 我事先知道所有的网址:

baseURL = // a https URL;
urlMap = new HashMap<String, URL>();
urlMap.put("login", new URL(baseURL, "exec.asp?login=username&pass=XPTO"));
urlMap.put("logout", new URL(baseURL, "exec.asp?exec.asp?page=999"));
urlMap.put("file", new URL(baseURL, "exec.asp?file=111"));

如果我在像Firefox这样的网络浏览器中尝试所有这些链接,它们都能正常工作。

现在我做的时候:

urlConnection = urlMap.get("login").openConnection();
urlConnection.connect();
BufferedReader in = new BufferedReader(
    new InputStreamReader(urlConnection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
    System.out.println(inputLine);
in.close();

我刚刚再次返回登录页面HTML,我无法继续下载文件。

谢谢!

有帮助吗?

解决方案

我同意Alnitak的观点,即问题可能是存储和返回Cookie。

我使用的另一个不错的选择是来自Jakarta Commons的 HttpClient

值得注意的是,如果这是您控制的服务器,您应该知道将用户名和密码作为查询字符串发送是不安全的(即使您使用的是HTTPS)。 HttpClient支持使用POST发送参数,您应该考虑这些参数。

其他提示

如前所述,您必须在请求之间维护会话cookie(请参阅 CookieHandler )。

以下是一个示例实现:

class MyCookieHandler extends CookieHandler {

    private Map<String, List<String>> cookies = new HashMap<String, List<String>>();

    @Override
    public Map<String, List<String>> get(URI uri,
            Map<String, List<String>> requestHeaders) throws IOException {
        String host = uri.getHost();
        Map<String, List<String>> ret = new HashMap<String, List<String>>();
        synchronized (cookies) {
            List<String> store = cookies.get(host);
            if (store != null) {
                store = Collections.unmodifiableList(store);
                ret.put("Cookie", store);
            }
        }

        return Collections.unmodifiableMap(ret);
    }

    @Override
    public void put(URI uri, Map<String, List<String>> responseHeaders)
            throws IOException {
        List<String> newCookies = responseHeaders.get("Set-Cookie");
        if (newCookies != null) {
            String host = uri.getHost();
            synchronized (cookies) {
                List<String> store = cookies.get(host);
                if (store == null) {
                    store = new ArrayList<String>();
                    cookies.put(host, store);
                }
                store.addAll(newCookies);
            }
        }
    }

}

尽管您可能遇到其他一些阻止登录请求登录的问题,但除非您存储并返回登录页面生成的任何Cookie,否则您不太可能继续访问下载页面。 / p>

这是因为HTTP本身是无状态的,因此在您当前的代码中,远程服务器无法告知第二个下载请求来自刚刚登录的同一用户。

也许您想尝试 HttpUnit 。尽管在编写网站测试时,它可能适用于您的问题。

从他们的网站:

&quot; ...用Java编写,HttpUnit模拟浏览器行为的相关部分,包括表单提交,JavaScript,基本http身份验证,cookie和自动页面重定向,并允许Java测试代码以文本形式检查返回的页面, XML DOM,或表单,表和链接的容器。“

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top