php - PHP:在 cURL GET 请求之后立即发出 cURL POST 请求
问题描述
我正在尝试在我的第一个 cURL 请求之后立即执行 cURL POST 请求。我是 PHP 和服务器端的新手。
我的第一个请求是 GET。通过 API 响应,我正在执行if error -> curl_close 或 else -> new cURL POST request。但是第二个请求什么也没返回。我已经尝试过使用“传统邮递员 JSON 请求”并且请求有效,所以问题出在我的 PHP 代码中。
/* First we try to have id user from his mail*/
$curl = curl_init();
$usermail = "user@mail.com";
//url = url + email
$gen_url = "https://myendpoint.com/manage/v1/user?search_text=";
$url = $gen_url.$usermail;
//GET request return all info about user, we do this to have his userid
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"Authorization: Bearer $tokenDecode",
"Content-Type: application/x-www-form-urlencoded",
),
));
$response2 = curl_exec($curl);
$err = curl_error($curl);
if ($err) {
echo "cURL Error #:" . $err;
curl_close($curl);
} else {
$userInfo = json_decode($response2, true);
$userId = $userInfo["data"]["items"][0]["user_id"] . "<br>";
/* We have the user_id, we can POST on user's additionnal fields */
$gen_url2="https://myendpoint.com/manage/v1/user/";
$url2= $gen_url2.$userId;
curl_setopt_array($curl, array(
CURLOPT_URL => $url2,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "PUT",
CURLOPT_POSTFIELDS => "{'additional_fields':[{'id':98,'value':2}]",
CURLOPT_HTTPHEADER => array(
"Authorization: Bearer $tokenDecode",
"Content-Type: application/json",
),
));
$response3 = curl_exec($curl);
$err2 = curl_error($curl);
curl_close($curl);
if ($err2) {
echo "cURL Error #:" . $err2;
} else {
echo $response3; //Show nothing
}
}
我的 GET 请求工作,我能够返回我想要的。但似乎我的第二个 cURL 请求没有发送,它没有返回任何响应。我正在做或认为的方式是错误的吗?还是我错过了什么?
谢谢
解决方案
如果 GET 请求正常,您可以在为 POST 请求设置数据之前通过curl_reset
(https://www.php.net/manual/en/function.curl-reset.php )重置 curl 数据。
推荐阅读
- python - 如何合并不同嵌套级别的嵌套字典?
- angularjs - 在学习 Angular 4-6 之前需要学习 AngularJS 吗?
- php - 忽略 PHP 函数中的本地化转换
- qt - Qt:在 SQLite 数据库上捕获外部更改
- html - 垂直对齐:在多行文本之后
- angular - 如何在 Angular 中执行代码之前等待 API 响应
- objective-c - 目标-c:当数据来自字符串时,NSJSONSerialization 失败
- java - 通过 MessageMapping 验证 spring websocket
- mysql - 如何添加“created_at”和“updated_at”列?
- javascript - 如何检查它是否是foreach循环中的最后一个元素