如何在PHP中使用JSON格式发送POST请求

时间:2014-11-04 23:41:37

标签: php json post

我已经能够使用chrome的Advanced Rest Client Extension将POST查询发送到特定的URL以及以下代码:

作为标题,我输入了这个:

Accept: application/json
version: 1.0.2
Authorization: code sadkj4-sadj-as22-asdk2

身体:

{
   "email" : "$email",    <====PHP variable passed as argument
   "password" : "$password",  <====PHP variable passed as argument
   "UserVerified" : true, 
   "notificationOption" :
      [
         {
            "notificationType" : "NOTIFICATION1",
            "enabled" : true
         },
         {
            "notificationType" : "NOTIFICATION2",
            "enabled" : false
         },
         {
            "notificationType" : "NOTIFICATION3",
            "enabled" : true
         },
         {
            "notificationType" : "NOTIFICATION4",
            "enabled" : true
         },
         {
            "notificationType" : "NOTIFICATION5",
            "enabled" : true
         },
         {
            "notificationType" : "NOTIFICATION6",
            "enabled" : true
         }
      ],
    "cap":"uc",
    "GeneratedPassword":true
}

并将Content-Type设置为:application / json

我通过发送请求的URL成功获得响应,但现在我想创建一个PHP函数,只需传递值$ email和$ password作为参数即可。

我听说有人说我应该使用guzzle来完成这项任务,但我不知道怎么做,而且如果我不需要,我也不想使用第三方库。有没有其他方法可以做到这一点? 任何有关这方面的帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

你需要一个HTTP客户端库与web服务器交互,guzzle就是其中之一,另一个例子是Zend \ Http。如果你在没有库的情况下这样做可能会很麻烦,因为你必须自己管理HTTP标题,正文,网址等。

下一个最简单的方法是使用PHP curl库,硬核方法是使用PHP套接字实现所有内容。

答案 1 :(得分:0)

如果可能,请使用cURL。在$json_string_data

中准备您的json数据,包括电子邮件/密码
$json_string_data = '{"email" : "' . $email . '", "password" : "' . $password . '", ...}';
$ch = curl_init('http://your_api_url');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_string_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'version: 1.0.2',
    'Authorization: code sadkj4-sadj-as22-asdk2',
    'Content-Length: ' . strlen($json_string_data))
);
$result = curl_exec($ch);
相关问题