Helper function to issue a HTTP request with simpletest's cURL.
string $url: The relative URL, e.g. "entity/node/1"
string $method: HTTP method, one of GET, POST, PUT or DELETE.
array $body: Either the body for POST and PUT or additional URL parameters for GET.
string $mime_type: The MIME type of the transmitted content.
protected function httpRequest($url, $method, $body = NULL, $mime_type = NULL) {
if (!isset($mime_type)) {
$mime_type = $this->defaultMimeType;
}
if (!in_array($method, array(
'GET',
'HEAD',
'OPTIONS',
'TRACE',
))) {
// GET the CSRF token first for writing requests.
$token = $this
->drupalGet('rest/session/token');
}
switch ($method) {
case 'GET':
// Set query if there are additional GET parameters.
$options = isset($body) ? array(
'absolute' => TRUE,
'query' => $body,
) : array(
'absolute' => TRUE,
);
$curl_options = array(
CURLOPT_HTTPGET => TRUE,
CURLOPT_URL => url($url, $options),
CURLOPT_NOBODY => FALSE,
CURLOPT_HTTPHEADER => array(
'Accept: ' . $mime_type,
),
);
break;
case 'POST':
$curl_options = array(
CURLOPT_HTTPGET => FALSE,
CURLOPT_POST => TRUE,
CURLOPT_POSTFIELDS => $body,
CURLOPT_URL => url($url, array(
'absolute' => TRUE,
)),
CURLOPT_NOBODY => FALSE,
CURLOPT_HTTPHEADER => array(
'Content-Type: ' . $mime_type,
'X-CSRF-Token: ' . $token,
),
);
break;
case 'PUT':
$curl_options = array(
CURLOPT_HTTPGET => FALSE,
CURLOPT_CUSTOMREQUEST => 'PUT',
CURLOPT_POSTFIELDS => $body,
CURLOPT_URL => url($url, array(
'absolute' => TRUE,
)),
CURLOPT_NOBODY => FALSE,
CURLOPT_HTTPHEADER => array(
'Content-Type: ' . $mime_type,
'X-CSRF-Token: ' . $token,
),
);
break;
case 'PATCH':
$curl_options = array(
CURLOPT_HTTPGET => FALSE,
CURLOPT_CUSTOMREQUEST => 'PATCH',
CURLOPT_POSTFIELDS => $body,
CURLOPT_URL => url($url, array(
'absolute' => TRUE,
)),
CURLOPT_NOBODY => FALSE,
CURLOPT_HTTPHEADER => array(
'Content-Type: ' . $mime_type,
'X-CSRF-Token: ' . $token,
),
);
break;
case 'DELETE':
$curl_options = array(
CURLOPT_HTTPGET => FALSE,
CURLOPT_CUSTOMREQUEST => 'DELETE',
CURLOPT_URL => url($url, array(
'absolute' => TRUE,
)),
CURLOPT_NOBODY => FALSE,
CURLOPT_HTTPHEADER => array(
'X-CSRF-Token: ' . $token,
),
);
break;
}
$response = $this
->curlExec($curl_options);
$headers = $this
->drupalGetHeaders();
$headers = implode("\n", $headers);
$this
->verbose($method . ' request to: ' . $url . '<hr />Code: ' . curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE) . '<hr />Response headers: ' . $headers . '<hr />Response body: ' . $response);
return $response;
}