2012-08-01 114 views
0

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

产地Java代码:

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(); 
+0

在发出下一个请求之前,您需要'conn.getresponse()。read()'。为了生成'x-www-form-urlencoded''内容,你可以使用'urllib.urlencode(dict(version = 2,request = data))''。 – jfs 2012-08-01 16:32:00

+0

强烈建议您查看使用[requests](http://docs.python-requests.org/en/latest/index.html)而不是httplib – jterrace 2012-08-01 16:38:01

+0

您应该先阅读Javadoc,或者事实上不要问这样的问题。不同之处在于它们不一样。真的没有什么可说的。 – EJP 2012-08-01 22:33:51

回答