我已经成功实现了HTTPS页面的调用,并且HTTP基本认证也能正常使用,但我无法在HTTPS连接上运行基本认证功能。
我附上了代码示例,但它不起作用。我一直得到一个403错误。我已经检查了用户名和密码,在Firefox浏览器上使用RESTClient插件测试时也是成功的。
希望能得到任何帮助。谢谢。
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();
}
}