php - 如何在 cURL php 中发布 JSON 数据和请求 token (在 header 中)

标签 php azure curl

我想以 JSON 数据形式发送登录凭据和 PIN 码,并以 http header 形式发送请求 token 。

一开始是这样的

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

我还需要发布我的请求 header token

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

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

} 

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

我尝试将请求 token 保存到变量中,并将其传递到 header 中,并将用户名、密码和 pinnumber 作为 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 ;
}

最佳答案

在上面的代码中,您为 curl_init() 设置了一个 URL,并且还在 CURLOPT_URL 选项中传递了另一个 URL。您无法在一个 cURL 请求中执行此操作。

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

更多信息请引用PHP manual on cURL Functions

关于php - 如何在 cURL php 中发布 JSON 数据和请求 token (在 header 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47234874/

相关文章:

php - 提交前验证表单

c# - 并行查询 Azure 存储

java - REST API 聚合 实时

php - Http 400 错误请求 - 波斯语 URL 中的 Php file_get_contents

javascript - 在 session 中放置一个列表并显示每个 session

php - 将文本列转换为时间

php - 要捕获的动态正则表达式

c# - 可以在 .NET 应用程序中等待 1000 个任务的集合吗?或者应该使用批处理?

azure - 如何使用 Kusto 访问 Azure Function 应用代码logging() 消息?

java - 在 Java 中为 SOLR curl 等效的 POST