【问题标题】:How to post JSON data and a request token(in the header) in cURL php如何在 cURL php 中发布 JSON 数据和请求令牌(在标头中)
【发布时间】:2017-11-11 05:56:04
【问题描述】:

我想将登录凭据和 pin 号作为 JSON 数据发送,并将请求令牌作为我的 http 标头发送。

一开始是这样的,

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

我还需要发布我的请求标头令牌

如果请求正常,我应该得到如下 JSON 响应,

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

} 

我正在尝试在 cURL PHP 中执行此操作。下面是我的控制器代码。

我尝试将我的请求令牌保存到一个变量中并将其传递到标头中,并将用户名、密码和密码作为 JSON 数据发布。如果登录成功,则应显示用户信息。但我正在努力从这里继续前进。我怎样才能做到这一点?

public function send_data() {

$url='http://samplesite.azurewebsites.net/api/member/loginmember';

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


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


//echo $data_string; 

// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");

curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); 

curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json',                                                                                
    'Content-Length: ' . strlen($data_string))                                                                       
); 
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);


//var_dump(json_decode($result, true));
$data2=json_decode($result, true);
$ref_id = ( ( is_array( $data2["UserCode"] ) ? implode(", ", $data2["PinCode"]) : $data2["RequestToken"] ) ); // array to string
$acc_t = $data2["RequestToken"];
$uun = $data2["UserCode"];

//echo $acc_t;


// Closing
curl_close($ch);
//print  $result ;
}

【问题讨论】:

    标签: php azure curl


    【解决方案1】:

    在上面的代码中,您将 URL 设置为 curl_init(),并且还在 CURLOPT_URL 选项中传递了另一个 URL。你不能在一个 cURL 请求中做到这一点。

    如果您使用的是 OAuth 2.0,您可以将访问令牌设置为 CURLOPT_XOAUTH2_BEARER 选项。

    更多信息,请参考PHP manual on cURL Functions

    【讨论】:

      猜你喜欢
      • 2018-04-24
      • 1970-01-01
      • 2017-10-29
      • 2016-11-19
      • 1970-01-01
      • 2020-01-28
      • 2021-02-24
      • 2013-08-14
      • 2021-03-03
      相关资源
      最近更新 更多