2012-03-13 254 views
0

我正在嘗試使用http url調用sms api。我試圖在php.I中使用curl調用url。我得到了一個BAD REQUEST錯誤。請解釋我我做錯了。CURL:嘗試調用http url時發生錯誤請求錯誤

// create a new cURL resource 
    $ch = curl_init(); 
    $string1 = "http://api.znisms.com/post/smsv3.asp?userid=alpesh67&apikey=74c6314840a16c5e7db00415a03181f7&message= Congratulation you have been successfully registered in the Placement Management System \n Email:".$email."\n Password:".$password."&senderid=PMS12345&sendto=".$contactno.""; 
    echo $string1; 
    // set URL and other appropriate options 
    curl_setopt($ch, CURLOPT_URL, $string1); 
    // grab URL and pass it to the browser 
    curl_exec($ch); 
    //close cURL resource, and free up system resources 
    curl_close($ch); 
    //SMS END 

我得到以下錯誤:

http://api.znisms.com/post/smsv3.asp?userid=alpesh67&apikey=74c6314840a16c5e7db00415a03181f7&message= Congratulation you have been successfully registered in the Placement Management System Email:[email protected] Password:123456789&senderid=PMS12345&sendto=9773396773 
Bad Request 

回答

9

在URL中不能使用空格。你需要URL編碼字符串:

&message= Congratulation you have been successfully registered in the Placement Management System \n Email:".$email."\n Password:".$password." 

http://php.net/manual/en/function.urlencode.php

Returns a string in which all non-alphanumeric characters except -_. have been replaced with a percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs. It is encoded the same way that the posted data from a WWW form is encoded, that is the same way as in application/x-www-form-urlencoded media type. This differs from the » RFC 3986 encoding (see rawurlencode()) in that for historical reasons, spaces are encoded as plus (+) signs.

我會做一些事情來的效果:

// create a new cURL resource 
    $ch = curl_init(); 
    $encoded_message = urlencode("Congratulation you have been successfully registered in the Placement Management System \n Email:".$email."\n Password:".$password) 
    $string1 = "http://api.znisms.com/post/smsv3.asp?userid=alpesh67&apikey=74c6314840a16c5e7db00415a03181f7&message=".$encoded_message."&senderid=PMS12345&sendto=".$contactno.""; 
    echo $string1; 
    // set URL and other appropriate options 
    curl_setopt($ch, CURLOPT_URL, $string1); 
    // grab URL and pass it to the browser 
    curl_exec($ch); 
    //close cURL resource, and free up system resources 
    curl_close($ch); 
    //SMS END 
+0

我曾嘗試只需撥打從網頁瀏覽器中創建的URL,並將其works.So消息中的空間是沒有問題的。但我仍然嘗試了您的解決方案,但我仍然遇到了錯誤。 – Jonah 2012-03-13 12:43:04

+0

你有更新的錯誤嗎?錯誤中URL的內容應與添加的urlencode()不同。 – Drahkar 2012-03-13 13:01:41

+0

urlencode函數爲我做了訣竅。謝謝 – noobcode 2013-02-03 14:23:41

1

這可能是由於被用空格傳遞的信息在網址中。 嘗試urlencod

1

在url上使用urlencode(),因爲有空格。此外,它是很好的做法,包括捲曲heaader如下:

$headers = array("User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.8) Gecko/20061025 Firefox/1.5.0.8"); 

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 
相關問題