基本上,我需要通过http GET请求访问“安全”(过时的证书)服务器,并在标头中使用基本身份验证并打印(现在)我从中获取的XML。我在C#上运行代码,如下:
var request = HttpWebRequest.CreateHttp(new Uri(BaseUri, apiUrl));
request.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
if (accept != null)
request.Accept = accept;
request.ServerCertificateValidationCallback = (s, crt, chain, ssl) => true;
AddAuthHeaderBasicFromCredentials(request, ApiCredentials);
try
{
var response = request.GetResponse();
return response.GetResponseStream();
}
catch (WebException)
{
return null;
}
就我的java代码而言,这就是我所拥有的:
public class Main {
static {
//for localhost testing only
javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(
new javax.net.ssl.HostnameVerifier(){
public boolean verify(String hostname,
javax.net.ssl.SSLSession sslSession) {
return true;
}
});
}
public static void main(String[] args) {
try {
String webPage = "https://blabla.com";
String name = "user";
String password = "pass";
String authString = name + ":" + password;
System.out.println("auth string: " + authString);
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
System.out.println("Base64 encoded auth string: " + authStringEnc);
URL url = new URL(webPage);
HttpURLConnection HttpurlConnection = (HttpURLConnection) url.openConnection();
HttpurlConnection.setRequestMethod("GET");
HttpurlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
InputStream is = HttpurlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int numCharsRead;
char[] charArray = new char[1024];
StringBuffer sb = new StringBuffer();
while ((numCharsRead = isr.read(charArray)) > 0) {
sb.append(charArray, 0, numCharsRead);
}
String result = sb.toString();
System.out.println("*** BEGIN ***");
System.out.println(result);
System.out.println("*** END ***");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
它可以在任何不需要身份验证的网站上正常工作,但每当我尝试访问网站时,我的目标都是出错:
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException:
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException:
unable to find valid certification path to requested target
课程开始时的静态块是我试图绕过我在证书上遇到的问题。我知道这不是推荐的方法,但这只是一个测试,我需要它来运行。
提前致谢,我很乐意提供您可能需要的任何信息。