如何将python httplib.HTTPSConnection转换为php

时间:2014-06-19 09:59:45

标签: php python

我希望用php发送一个HTTPS后请求,类似于python中的请求:

API_HOST = "android.clients.google.com"
API_PAGE = "/market/api/ApiRequest"
parmas=params = urllib.urlencode({
  "version" : 2,
  "request" : request
})
headers = {"Content-type": "application/x-www-form-urlencoded"}
connection = httplib.HTTPSConnection( API_HOST )
connection.request( "POST", API_PAGE, params, headers )
resp = connection.getresponse().read()
connection->close()

我试过这个lib https://github.com/dcramer/php-httplib

但是这个lib,不支持HTTPS

我的PHP代码:

$query_data = array(
  "version" => 2,
  "request" => $request
);
$params = http_build_query($query_data);
$headers = array("content-type"=> "application/x-www-form-urlencoded");
$API_URL =  $API_HOST.$API_PAGE;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $API_URL);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$resp = curl_exec($ch);

python代码有效,但php代码返回错误请求,错误400

1 个答案:

答案 0 :(得分:0)

你可以试试这个:

<?php

// Data
$postfields = array(
    'version' => 2,
    'request' => $request
);

// Post It
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://android.clients.google.com/market/api/ApiRequest');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$result = curl_exec($ch);
curl_close($ch);

// Debug
var_dump($result);