Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send string in PUT request with libcurl

Tags:

c

curl

My code looks like this:

curl = curl_easy_init();

if (curl) {
    headers = curl_slist_append(headers, client_id_header);
    headers = curl_slist_append(headers, "Content-Type: application/json");

    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); 
    curl_easy_setopt(curl, CURLOPT_URL, "127.0.0.1/test.php");  
    curl_easy_setopt(curl, CURLOPT_PUT, 1L);

    res = curl_easy_perform(curl);
    res = curl_easy_send(curl, json_struct, strlen(json_struct), &io_len);

    curl_slist_free_all(headers);
    curl_easy_cleanup(curl);
}

Which doesnt work, the program just hangs forever.

In test.php these are the request headers I get:

array(6) {
  ["Host"]=>
  string(9) "127.0.0.1"
  ["Accept"]=>
  string(3) "*/*"
  ["Transfer-Encoding"]=>
  string(7) "chunked"
  ["X-ClientId"]=>
  string(36) "php_..."
  ["Content-Type"]=>
  string(16) "application/json"
  ["Expect"]=>
  string(12) "100-continue"
}

But the body is empty, means, no json data is sent with the request.

What I want to do with libcurl is actually nothing else then these command line script:

curl -X PUT -H "Content-Type: application/json" -d '... some json ...' 127.0.0.1/test.php
like image 968
Max Avatar asked Sep 27 '11 13:09

Max


2 Answers

Got it :)

Dont use

curl_easy_setopt(curl, CURLOPT_PUT, 1L);

Make a custom request and send the data as POSTFIELDS:

curl = curl_easy_init();

if (curl) {
    headers = curl_slist_append(headers, client_id_header);
    headers = curl_slist_append(headers, "Content-Type: application/json");

    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); 
    curl_easy_setopt(curl, CURLOPT_URL, request_url);  
    curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT"); /* !!! */

    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_struct); /* data goes here */

    res = curl_easy_perform(curl);

    curl_slist_free_all(headers);
    curl_easy_cleanup(curl);
}
like image 157
Max Avatar answered Sep 28 '22 01:09

Max


CURLOPT_PUT is deprecated, and has been for a while. You should use CURLOPT_UPLOAD.

For unknown amounts of data with HTTP, you should be using chunked transfer encoding. The CURLOPT_UPLOAD docs say:

If you use PUT to a HTTP 1.1 server, you can upload data without knowing the size before starting the transfer if you use chunked encoding. You enable this by adding a header like "Transfer-Encoding: chunked" with CURLOPT_HTTPHEADER. With HTTP 1.0 or without chunked transfer, you must specify the size.

like image 32
Nathan Ward Avatar answered Sep 28 '22 02:09

Nathan Ward