java HttpsURLConnection和python HTTPSConnection有什么区别?

时间:2012-08-01 15:09:55

标签: java python https

我想将开源项目android-market-api从java移植到python。但现在我已经陷入了https问题。 当我使用HTTPSConnection请求https://android.clients.google.com/market/api/ApiRequest时,它总是返回403.经过一些调试后,我认为可能是Java HttpsURLCollection和python HTTPSConnection之间存在一些区别。

Python端口:

headers = {
    'Cookie': 'ANDROIDSECURE=' + auth_key,
    'User-Agent': 'Android-Market/2 (sapphire PLAT-RC33); gzip',
    'Content-Type': 'application/x-www-form-urlencoded',
    'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
    'Accept': 'text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2',
    'Connection': 'keep-alive'
}
conn = httplib.HTTPSConnection('android.clients.google.com')
conn.request('POST', '/market/api/ApiRequest', 'version=2&request=' + urlsafe_b64encode(data), headers)

Origin java code:

TrustManager[] trustAllCerts = new TrustManager[]{
        new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
            public void checkClientTrusted(
                java.security.cert.X509Certificate[] certs, String authType) {
            }
            public void checkServerTrusted(
                java.security.cert.X509Certificate[] certs, String authType) {
            }
        }
    };

SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier()
{
    public boolean verify(String arg0, SSLSession arg1) {
        return true;
    }
});

URL url = new URL("https://android.clients.google.com/market/api/ApiRequest");
HttpsURLConnection cnx = (HttpsURLConnection)url.openConnection();
cnx.setDoOutput(true);
cnx.setRequestMethod("POST");
cnx.setRequestProperty("Cookie","ANDROIDSECURE=" + this.getAuthSubToken());
cnx.setRequestProperty("User-Agent", "Android-Market/2 (sapphire PLAT-RC33); gzip");
cnx.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
cnx.setRequestProperty("Accept-Charset","ISO-8859-1,utf-8;q=0.7,*;q=0.7");
String request64 = Base64.encodeBytes(request,Base64.URL_SAFE);
String requestData = "version="+PROTOCOL_VERSION+"&request="+request64;
cnx.setFixedLengthStreamingMode(requestData.getBytes("UTF-8").length);
OutputStream os = cnx.getOutputStream();
os.write(requestData.getBytes());
os.close();

1 个答案:

答案 0 :(得分:0)

403表示请求成功,即"the provided credentials were successfully authenticated but that the credentials still do not grant the client permission to access the resource",例如,没有正确的标题,正文我得400而非403

这里有一个关于如何make https request using httplib的更完整的例子。