I'm trying to post a request to a REST service using curl in PHP, but it is not working. Listed below is the piece of code, I have tried.
function curl_post_data($log,$url){
$clientid= 18;
$userid = 1614;
$voicesample1filename = realpath("RecordFiles/utterance1.wav");
$voicesample2filename = realpath("RecordFiles/utterance2.wav");
$voicesample3filename = realpath("RecordFiles/utterance3.wav");
$payload['sessionid'] = '13738B27-C664-57B0-2ABF-8873914E971A';
$payload['clienid'] = $clientid;
$payload['userid'] = $userid;
$payload['type'] = 8;
$payload['action'] = 'registration';
// build multipart
$payload = http_build_query($payload);
if ( is_file($voicesample1filename) ) {
$log->LogInfo("File '" . $voicesample1filename . "' exists");
} else {
$log->LogInfo("File '" . $voicesample1filename . "' does not exists");
}
$params = "--ABC1234\r\n"
. "Content-Type: application/x-www-form-urlencoded\r\n"
. "\r\n"
. $payload . "\r\n"
. "--ABC1234\r\n"
. "Content-Type: audio/wav\r\n"
. "Content-Disposition: attachment; utterance1=\"attachment1.wav\"\r\n"
. "\r\n"
. file_get_contents($voicesample1filename) . "\r\n"
. "--ABC1234\r\n"
. "Content-Type: audio/wav\r\n"
. "Content-Disposition: attachment; utterance2=\"attachment2.wav\"\r\n"
. "\r\n"
. file_get_contents($voicesample2filename) . "\r\n"
. "--ABC1234\r\n"
. "Content-Type: audio/wav\r\n"
. "Content-Disposition: attachment; utterance3=\"attachment3.wav\"\r\n"
. "\r\n"
. file_get_contents($voicesample3filename) . "\r\n"
. "--ABC1234--";
$log->LogInfo("Request is :" .$params);
$first_newline = strpos($params, "\r\n");
$multipart_boundary = substr($params, 2, $first_newline - 2);
$request_headers = array();
$request_headers[] = 'Content-Length: ' . strlen($params);
$request_headers[] = 'Content-Type: multipart/form-data; boundary='. $multipart_boundary;
$log->LogInfo("PayLoad Array is :" .print_r($payload,true));
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
//curl_setopt($ch, CURLOPT_PUT, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);
$reply = curl_exec($ch);
$arrayOfResult=json_decode($reply,true);
}
If I execute the code, I'm getting multipart request error.
You don't need to use the 'Content-Disposition' things manually. Curl does it automatically when it finds a file to send. You can consider the following example for this case. curl will adjust the required multipart headers if you use something similar with your code.
$params = array("name" => "some-name",
"id" => "1231",
"file1" => "@c:/temp/file1.wav",
"file2" => "@c:/temp/file2.wav"
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.