gpt4 book ai didi

java - 基于 HTTPS Java 的基本身份验证

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:38:56 24 4
gpt4 key购买 nike

我的 HTTPS 页面调用工作正常,我的 HTTP Basic Auth 工作正常但我不能做的是让 Basic Auth 在 HTTPS 连接上运行。

我附上了一个代码示例,但它不起作用。我一直收到 403。我已经检查了用户名和密码,并且在使用 RESTClinet 测试它时成功了。来自 Firefox 的插件。

任何帮助都会很棒。谢谢。

   private static void getAPITest() throws MalformedURLException, IOException 
{
try {


System.setProperty("javax.net.ssl.trustStore","/home/USER/CERTS/myTrustStore");
System.setProperty("javax.net.ssl.trustStorePassword", "PASSWORD");


Authenticator myAuth = new Authenticator()
{
@Override
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication("USERNAME", "PASSWORD".toCharArray());
}
};

Authenticator.setDefault(myAuth);


String httpsURL = "https://someurlandapi.com";
URL myurl = new URL(httpsURL);
HttpsURLConnection con = (HttpsURLConnection)myurl.openConnection();
//con.setRequestProperty("Authorization", "Basic " + authString);
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setRequestProperty("Accept", "application/json");
con.setRequestMethod("POST");

InputStream ins = con.getInputStream();
InputStreamReader isr = new InputStreamReader(ins);
BufferedReader in = new BufferedReader(isr);

String inputLine;

while ((inputLine = in.readLine()) != null)
{
System.out.println(inputLine);
}

ins.close();
in.close();

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

最佳答案

原来在basic之前没有空格:

con.setRequestProperty("Authorization", "Basic " + authStringEnc);

它需要:

conn.setRequestProperty("User-Agent", "Mozilla/5");

如果您要创建自己的信任库,您将需要添加站点/网址 SSL 证书链,这是给任何执行此操作的人的快速说明。在 firefox 中,您可以单击挂锁 > 更多信息 > 安全 > 查看证书。从那里您可以突出显示带有链接的证书导出,然后使用 key 工具将其添加到您的信任库:

keytool -import -file websitecertificate.pem -alias websitecert -keystore myTrustStore

关于java - 基于 HTTPS Java 的基本身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36726023/

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