从URL读取文件时出现问题 - 权限被拒绝

时间:2011-07-25 12:35:43

标签: java

我试图连接到像这样的主机

                url = new URL(urlString);
                BufferedReader in = new BufferedReader(
                                new InputStreamReader(
                                url.openStream()));

但我总是得到MalformedException - 权限被拒绝,我需要提供用户名和密码(我知道),但我不知道如何,URL中没有构造函数,这些参数既不是setusername / password方法。在哪里输入用户名和密码?

3 个答案:

答案 0 :(得分:1)

我从来没有遇到过这样的问题但是....试着看看这个:

class urllib2.HTTPPasswordMgr     保留(realm,uri)的数据库 - > (用户,密码)映射。

也许它会有所帮助 有关此链接的URLLIB2的文档:

http://docs.python.org/library/urllib2.html

希望它会有所帮助

答案 1 :(得分:1)

如果是HTTP身份验证,请使用http://user:password@server:80/path形式的网址 如果是应用程序身份验证,请提交带有详细信息的POST / GET HTTP请求。

答案 2 :(得分:1)

我曾在之前的项目中这样做过。要访问受保护的资源,您需要使用Authenticator类。

用户名和密码在最后为它们定义的变量中,但它们不需要硬编码,您可以使用java属性将它们外部化。

这是一个旧代码段

// Install the custom authenticator
Authenticator.setDefault(new MyAuthenticator());

// Access the page
try {
    // Create a URL for the desired page
    URL url = new URL("THE URL YOU NEED TO OPEN/ACCESS");

    // Read all the text returned by the server
    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
    String str;
    while ((str = in.readLine()) != null) {
        // str is one line of text; readLine() strips the newline character(s)
    }
    in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}

public class MyAuthenticator extends Authenticator {
    // This method is called when a password-protected URL is accessed
    protected PasswordAuthentication getPasswordAuthentication() {
        // Get information about the request
        String promptString = getRequestingPrompt();
        String hostname = getRequestingHost();
        InetAddress ipaddr = getRequestingSite();
        int port = getRequestingPort();

        // Get the username from the user...
        String username = "myusername";

        // Get the password from the user...
        String password = "mypassword";

        // Return the information
        return new PasswordAuthentication(username, password.toCharArray());
    }
}