首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在php中发送json请求?

如何在php中发送json请求?
EN

Stack Overflow用户
提问于 2017-09-26 14:11:44
回答 1查看 910关注 0票数 1

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

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

我在网上找到的密码是:

代码语言:javascript
复制
$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 );

下面是我在测试本地时所面临的错误:

代码语言:javascript
复制
 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 server)时,没有错误,也没有结果(接收短信)

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

提前谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-09-26 20:02:34

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

您尝试调用的服务可能要求您从the服务器提供静态IP,因为它们只允许访问基于IP的级别。意思是,你的IP被封锁,直到他们允许。

我建议你使用cURL来完成你的请求。这样,如果有任何故障,您就可以获得用于调试的未来数据。在这里,如果服务没有响应,您需要获得任何其他信息。

代码语言:javascript
复制
$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。如果关闭,则可以获取错误或信息数据。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46428773

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档