我尝试将数据发送到外部rest api调用,他们将数据作为原始格式获取。
这是我的代码:
$headers = array('Authorization: XXXXXX', 'Content-Type: application/json');
$data = array('name' => 'test', 'age' => 26);
$post['data'] = json_encode($data);
$url = 'My external api url';
$process = curl_init();
curl_setopt($process, CURLOPT_TIMEOUT, 600000);
curl_setopt($process, CURLOPT_HEADER, 0);
curl_setopt($process, CURLOPT_HTTPHEADER, $headers);
curl_setopt($process, CURLOPT_URL, $url);
curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($process, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0 );
curl_setopt($process, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
$user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.7 ' .
'(KHTML, like Gecko) Chrome/7.0.517.41 Safari/534.7'; // imitate chrome
curl_setopt ($process, CURLOPT_USERAGENT, $user_agent);
if ($method == 'POST') {
curl_setopt($process, CURLOPT_POST, 1);
curl_setopt($process, CURLOPT_POSTFIELDS, $data);
}
elseif ($method == 'PUT') {
curl_setopt($process, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($process, CURLOPT_POSTFIELDS, http_build_query($data));
}
$response = curl_exec($process);
print_r($response);exit;
它给出了空响应。当我在REST API添加中尝试此操作时,它会给出正确的结果。
我想知道如何将表单体设置为原始类型,如form-data,binary&的X WWW窗体-urlencoded?
请参阅附图:
答案: 我试图以json格式传递输入。它对我有用。 这是示例输入:
{ "data":{ "name": "test", "age": 26 } }
答案 0 :(得分:-1)
试试这个:
curl_setopt($process, CURLOPT_HTTPHEADER, array('Content-Type: text/plain'));