使用cURL PHP

时间:2017-11-11 08:39:55

标签: php json curl

这是我的示例JSON请求

{
    "Username":"admin",
    "Password":"root123",
   "PinCode” : "hello321"
}

此外,我还要发布请求令牌,请求令牌必须作为请求标头发布。

当我成功发送这些数据和有效令牌时,我需要收到如下的jSON响应,

{
            "Title": "Mr.",
            "Name": "Pushkov",
            "Age": "18"

}   

我的问题是,

如何在PHP cURL中发布我上面提到的JSON数据和令牌,如果代码点火器中的细节错误,则显示错误?

这就是我到目前为止所做的...并且它没有给我确切的输出我正在寻找,我无法想出一种方法来发送我的令牌作为标题请求...

public function send_veri(){

$url='http://helloworld21.azurewebsites.net/api/member/login';

$ch = curl_init('http://localhost/apphome');


$data = array("Username" =>$this->input->post('un'), "Password"  =>$this->input->post('pw'), "PinCode" =>$this->input->post('VerificationCode'));                                                                    
$data_string = json_encode($data);   


// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

//curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); 

curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json',                                                                                
    'Content-Length: ' . strlen($data_string))                                                                       
); 
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Set the url
//curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
}

一旦我运行它,我只能获得用户名,密码和PinCode。我无法在我的标题中发布请求令牌,导致我无法获得成员详细信息响应。

1 个答案:

答案 0 :(得分:4)

发送数据 -

  public function send_veri(){
      $url='http://helloworld21.azurewebsites.net/api/member/login';
      $ch = curl_init( $url );
      $bodyData=json_encode(array()); // here you send body Data
      $data = json_encode(array("Username" =>$this->input->post('un'), "Password" =>$this->input->post('pw'), "PinCode" =>$this->input->post('VerificationCode')));

                    curl_setopt( $ch, CURLOPT_POSTFIELDS, $bodyData );

                    curl_setopt( $ch, CURLOPT_HTTPHEADER,  array("headerdata: ".$data.",Content-Type:application/json"));

                    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );

                    $result = curl_exec($ch);

                    curl_close($ch);
                   }

获取有关Apache服务器代码的标头数据 -

            $hEAdERS = apache_request_headers();
            $data = json_decode($hEAdERS['headerdata'], true);  
            echo $contentType=$hEAdERS['Content-Type'];
            echo $Username =  @trim($data['Username']);
            echo $Password =  @trim($data['Password']);
            echo $PinCode =  @trim($data['PinCode']);

它对我有用。