gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 00:39:21 25 4
gpt4 key购买 nike

我试图连接到这样的主机

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

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

最佳答案

我在之前的项目中曾这样做过。为了访问 protected 资源,您需要使用 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());
}
}

关于java - 从 URL 读取文件时出现问题 - 权限被拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6816210/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com