首先要做的是,作为他/她的评论中的nsfyn55,使用浏览器检查您的标题。有些网站会在返回响应之前检查用户代理 HTTP 标头。第二件事是,在使用 HTTPS 时,您需要正确初始化安全层。检查这个类:
public class SSLConfiguration {
private static boolean isSslInitialized = false;
private static final String PROTOCOL = "SSL";
public static boolean ACCEPT_ALL_CERTS = true;
public static void initializeSSLConnection() {
if (!isSslInitialized) {
if (ACCEPT_ALL_CERTS) {
initInsecure();
} else {
initSsl();
}
}
}
private static void initInsecure() {
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
@Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
}
};
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance(PROTOCOL);
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
}
HttpsURLConnection.setDefaultHostnameVerifier(
new HostnameVerifier() {
@Override
public boolean verify(String string, SSLSession ssls) {
return true;
}
});
isSslInitialized = true;
}
private static void initSsl() {
SSLContext sc = null;
try {
sc = SSLContext.getInstance(PROTOCOL);
} catch (NoSuchAlgorithmException ex) {
throw new RuntimeException(ex);
}
try {
sc.init(null, null, new SecureRandom());
} catch (KeyManagementException ex) {
throw new RuntimeException(ex);
}
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HostnameVerifier hv = new HostnameVerifier() {
@Override
public boolean verify(String urlHostName, SSLSession session) {
/* This is to avoid spoofing */
return (urlHostName.equals(session.getPeerHost()));
}
};
HttpsURLConnection.setDefaultHostnameVerifier(hv);
isSslInitialized = true;
}
}
连接很可能会失败 - 特别是如果网站没有正确的证书。在您的代码中,在您的类的构造函数中,插入以下代码:
SSLConfiguration.initializeSSLConnection();
还有一些需要考虑的事情 - 在openConnection
建议您添加以下内容之后:
con.setRequestMethod(METHOD);
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
但是,我倾向于相信,由于您从远程服务器获得响应,因此更多的是指定正确的标头,尤其是User-Agent
和Accept
. 如果上述方法不能帮助您解决问题,请打印出错误的堆栈跟踪并读取错误流(来自远程)以获得更有意义的错误消息。如果您使用 Firefox,Live HTTP Headers是一个非常方便的解决方案。在处理 HTTP 请求时,cURL也是最重要的命令行工具。