如何在php中发送json请求?

时间:2017-09-26 14:11:45

标签: php json http post

我有一个允许用户注册的注册页面。在注册之前我需要验证他们的电话号码。我已经给出了一个Web服务地址及其参数。 我给出的参数:

http://*********
Method:POST
Headers:Content-Type:application/json
Body:
the following in:
{
    "mobileNo":"0*********",
    "service":"****",
    "Code1":"*****",
    "content":"hi",
    "actionDate":"2017/09/26",
    "requestId":"1"
            }

这里是我在互联网上找到的代码:

$data = array(
  'mobileNo'      => '****',
  'service'    => '***',
  'Code1'       => '*****',
  'content' => '55',
  'actionDate'      => '2017/09/26');

$options = array(
'http' => array(
'method'  => 'POST',
'content' => json_encode( $data ),
'header'=>  "Content-Type: application/json" .
            "Accept: application/json"
)
);
$url =  "******";
$context  = stream_context_create( $options );
$result = file_get_contents( $url, false, $context );
$response = json_decode( $result );

这是我在测试本地时遇到的错误:

 file_get_contents(http://********/sms-gateway/sms-external-zone /receive): failed to open stream: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

当我在线测试时(cpanel服务器)没有错误,也没有结果(接收短信)

根据给定的参数,我哪里错了?

提前感谢。

1 个答案:

答案 0 :(得分:0)

根据您的错误,您的服务似乎没有响应。您是否尝试在浏览器中打开它,检查是否有任何响应?

您尝试呼叫的服务可能需要您从Web服务器提供静态IP,因为它们仅在基于IP的级别上授予访问权限。意思是,你的IP被阻止,直到它们允许它为止。

我建议您使用cURL来处理您的请求。这样,如果出现任何故障,您将获得用于调试的未来数据。仍在这里,如果服务没有响应,您需要获取任何其他信息。

$data = array(
  'mobileNo'      => '****',
  'service'    => '***',
  'Code1'       => '*****',
  'content' => '55',
  'actionDate'      => '2017/09/26');
$url =  "******";

$ch = curl_init( $url );
// set data as json string
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode($data));
// define json as content type
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
// tell curl to fetch return data
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
// follow location if redirect happens like http to https
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
// send request
$result = curl_exec($ch);

// gives you the result - most of the time you only want this
var_dump($result);

// for debugging purpose, gives you the whole connection info
var_dump(curl_getinfo($ch));

// gives back any occurred errors
var_dump(curl_error($ch));

curl_close($ch);

编辑:我添加了CURLOPT_FOLLOWLOCATION,因为请求可能会被重定向。我们也希望抓住这一点。我在最后添加了curl_close。如果它已关闭,则可以获取错误或信息数据。