2012-03-13 193 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);