更新:我正在抓取的網站爲我提供了另一種獲取所需數據的方式,因此我不再有這個問題。不過,我仍然對教育方面的解決方案感興趣。如何使用cURL將POST數據傳遞到JSON服務器
我想使用cURL通過POST將數據傳遞給JSON服務器。
我不知道如何格式化cURL的變量。
這不起作用(返回null):
define('POSTVARS', 'json='.urlencode('{"cid":"2623","strQuery":"","strValues":"undefined","currentPage":"0","pageSize":"-1","pageSort":"-1","countryId":"2","maxResultCount":""}'));
也沒有這個
define('POSTVARS', "json=%7B'cid'%3A'2623'%2C%20'strQuery'%3A''%2C%20'strValues'%3A'undefined'%2C%20'currentPage'%3A'0'%2C%20'pageSize'%3A'-1'%2C'pageSort'%3A'-1'%2C'countryId'%3A'2'%2C'maxResultCount'%3A''%7D=");
按Post JSON using Curl我設置的標頭
curl_setopt($ch, CURLOPT_HTTPHEADERS,array('Content-Type: application/json'));
我的腳本作品對於常規的POST變量,但不是當我嘗試將數據傳遞給JSON服務器時,我想知道是否我的數據格式不正確,或者必須提供其他附加參數。
我嘗試的完整代碼(格式如下一種破,我粘貼了完整的腳本這裏https://docs.google.com/document/d/1hokE6-oMtcs3MBgPUzPwJvZIWNABc3XjOO2IzbpxDF4/edit?hl=en&authkey=CKXcnv8C):
function get_url($url, $javascript_loop = 0, $timeout = 5) { $cookie = tempnam ("/tmp", "CURLCOOKIE"); $ch = curl_init(POSTURL); curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1"); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_ENCODING, ""); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_AUTOREFERER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); # required for https urls curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
$postvars=<<<HEREDOC
{'cid':'2623', 'strQuery':"", 'strValues':'undefined', 'currentPage':'0', 'pageSize':'-1','pageSort':'-1','countryId':'2','maxResultCount':''}
HEREDOC;
curl_setopt($ch, CURLOPT_POST ,1);
curl_setopt($ch, CURLOPT_POSTFIELDS ,$postvars);
curl_setopt($ch, CURLOPT_HEADER ,0); // DO NOT RETURN HTTP HEADERS
$arr = array();
array_push($arr, 'Content-Type: application/json; charset=utf-8');
curl_setopt($ch, CURLOPT_HTTPHEADER, $arr);
$content = curl_exec($ch);
$response = curl_getinfo($ch);
curl_close ($ch);
if ($response['http_code'] == 301 || $response['http_code'] == 302)
{
ini_set("user_agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1");
if ($headers = get_headers($response['url']))
{
foreach($headers as $value)
{
if (substr(strtolower($value), 0, 9) == "location:")
return get_url(trim(substr($value, 9, strlen($value))));
}
}
}
if ( (preg_match("/>[[:space:]]+window\.location\.replace\('(.*)'\)/i", $content, $value) || preg_match("/>[[:space:]]+window\.location\=\"(.*)\"/i", $content, $value)) &&
$javascript_loop < 5
)
{
return get_url($value[1], $javascript_loop+1);
}
else
{
return array($content, $response);
}
}
//設置網址 $ URL = 「http://us.asos.com/services/srvWebCategory.asmx/GetWebCategories」;
$ output = get_url($ url);
print_r($ output);
你使用CURLOPT_POSTFIELDS調用curl_setopt嗎? – Dereleased 2011-02-10 21:31:18