Skip to content

Instantly share code, notes, and snippets.

@alghanmi
Created May 5, 2014 20:12
Show Gist options
  • Save alghanmi/c5d7b761b2c9ab199157 to your computer and use it in GitHub Desktop.
Save alghanmi/c5d7b761b2c9ab199157 to your computer and use it in GitHub Desktop.
cURL C++ Example
#include <iostream>
#include <string>
#include <curl/curl.h>
static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp)
{
((std::string*)userp)->append((char*)contents, size * nmemb);
return size * nmemb;
}
int main(void)
{
CURL *curl;
CURLcode res;
std::string readBuffer;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "http://www.google.com");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
std::cout << readBuffer << std::endl;
}
return 0;
}
@alghanmi
Copy link
Author

alghanmi commented May 5, 2014

To run this example, you need to have the curl headers installed

#Install header files and library for cURL
sudo aptitude install libcurl4-openssl-dev
#Download sample cpp file
curl -sLO https://gist.github.com/alghanmi/c5d7b761b2c9ab199157/raw/curl_example.cpp
#Compile and run the code
g++ curl_example.cpp -o curl_example -lcurl
./curl_example

The only caveat is that when dealing with SSL connections, they need to use the OpenSSL libraries.

@irvin373
Copy link

irvin373 commented Apr 4, 2017

@alghanmi Works!!!!! your the best!!!!

@valhockey4
Copy link

Hello !
The curl example perfectly works ! What are the role of the "static size_t WriteCallback" function, the "if(curl)" and the "curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback)" ?
Thank you for your help.

@coroner4817
Copy link

@valhockey4

This callback function will be called when receive the http response from the server.
You need to pass a function to handle the response stored in contents. The CURLOPT_WRITEDATA is set the fourth param in the cb function. You can write the response to this buffer and access it at your user context.

@oelmekki
Copy link

oelmekki commented Apr 9, 2018

Note that you can't pass a std::string as url parameter for curl_easy_setopt:

std::string url = "http://www.google.com";
curl_easy_setopt(curl, CURLOPT_URL, url); // this will fail without triggering any compilation error (in g++, at least)
curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); // this will work

@thanhlev
Copy link

how can i use PUT or POST option in code? thank you!

@aftabnaveed
Copy link

aftabnaveed commented Jul 18, 2018

when i tried url.c_str() I got segmantation fault error. passing readBuffer by reference is also working in my app.

url has to be converted using url.c_str()

@shashiranjansjce
Copy link

Hi,
when i am giving wrong URL then it block with line
res = curl_easy_perform(curl);

is there any idea ,please suggest me.

Thanks in advance

@shashiranjansjce
Copy link

again posting more

int sendMsg(string toSend){

  int status = -1;
  CURL *curl;
 CURLcode res;
 string response;
  string url = "http://129.2.2.2/test.php";
  string data = "name="+toSend;
  curl_global_init(CURL_GLOBAL_ALL);

  curl = curl_easy_init();

  if(curl){
      curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
      curl_easy_setopt(curl, CURLOPT_POST, 1);
      curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.c_str());
      curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
     curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);

    res = curl_easy_perform(curl);  /------------------------  block here-------------------/

      if(res == 0)
	{

	}

}
}

it blocked at line res = curl_easy_perform(curl);

if i am giving correct url then working fine but blocked with wrong url. it should block, it should return error code.
please provide me suggestion.

@sumanthboppana
Copy link

res = curl_easy_perform(curl);
What is the use of "CURLcode res" variable? you have not used it further in above program? And what is the returning value to res variable?
Please help me..

@scribnermj
Copy link

scribnermj commented May 6, 2019

This code did work right out of the box for me.
With so many projects there are always little details.
This is a great example.
The follow-up message that includes the compiler line cinches it. -lcurl was essential to the compilation.

@abhishekaryan013
Copy link

How can i run this code in code block ?

@supern64
Copy link

supern64 commented Oct 7, 2019

Thank you so much for writing this as an example!

@pavel-shvetsov
Copy link

Hello,

For those folks who are looking for cURL + HTTPS - curl team has nice example on their project page:

Also there are tons of useful code snippets for many use cases: https://curl.haxx.se/libcurl/c/example.html

Copy link

ghost commented Dec 19, 2020

Where would one find the curl.h file in curl's source code? Is it on GitHub by any chance?

Incredible code nevertheless!

@sardar01
Copy link

sardar01 commented Feb 5, 2022

Works perfectly

@hasirciogli
Copy link

hasirciogli commented Nov 14, 2022

guys i dont know how to integrate my project can you halp me ?

Build started...
1>------ Build started: Project: cmk, Configuration: Release Win32 ------
1>cmk.cpp
1>cmk.obj : error LNK2001: unresolved external symbol _curl_easy_perform
1>cmk.obj : error LNK2001: unresolved external symbol _curl_easy_init
1>cmk.obj : error LNK2001: unresolved external symbol _curl_easy_strerror
1>cmk.obj : error LNK2001: unresolved external symbol _curl_easy_cleanup
1>cmk.obj : error LNK2001: unresolved external symbol _curl_easy_setopt
1>C:\Users\Mustafa_Owner\source\repos\cmk\Release\cmk.exe : fatal error LNK1120: 5 unresolved externals
1>Done building project "cmk.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
========== Elapsed 00:01,275 ==========

main.cpp - > \n
#include
#include <curl/curl.h>

int main()
{
CURL* curl;
CURLcode res;

curl = curl_easy_init();
if (curl) {
    curl_easy_setopt(curl, CURLOPT_URL, "https://example.com");

    /* Forcing HTTP/3 will make the connection fail if the server is not
       accessible over QUIC + HTTP/3 on the given host and port.
       Consider using CURLOPT_ALTSVC instead! */
    curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, (long)CURL_HTTP_VERSION_3);

    /* Perform the request, res will get the return code */
    res = curl_easy_perform(curl);
    /* Check for errors */
    if (res != CURLE_OK)
        fprintf(stderr, "curl_easy_perform() failed: %s\n",
            curl_easy_strerror(res));

    /* always cleanup */
    curl_easy_cleanup(curl);
}

}

@lukechikkala
Copy link

@hasirciogli

  1. It looks like you did not include the -lcurl library when you compiled, hence the "unresolved external symbol" errors.
  2. https://example.com does not support --http3, yet; you could test this using any HTTP/3 verifier.
    Try using any of the HTTP/3 supported websites, some are mentioned here.
  3. I compiled and executed your code using https://quic.tech but received a curl_easy_perform() failed: SSL connect error error.
    Most probably because I don't have the OpenSSL libraries installed, and this is expected.
    But the code itself is executing fine.
#include <curl/curl.h>

int main()
{
	CURL* curl;
	CURLcode res;
	curl = curl_easy_init();
	if (curl)
	{
		curl_easy_setopt(curl, CURLOPT_URL, "https://quic.tech");
		curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, (long)CURL_HTTP_VERSION_3);
		res = curl_easy_perform(curl);
		if (res != CURLE_OK)
			fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
		
		curl_easy_cleanup(curl);
	}
}

Hope that helps :)

@PardeepSangha
Copy link

I developed a client which is receiving data from server occasionally. But when I receive first data, then program exists. I tried while loop like windows message loop, but it gives me last data.

How can I stay in program so that I can receive more messages from server.

@voiduin
Copy link

voiduin commented Jul 21, 2024

@alghanmi Hi!

First off, thank you for sharing your code example! It was incredibly helpful for getting me started quickly. However, I wanted to point out a couple of discrepancies that I noticed:

  1. Missing global initialization:
    The libcurl documentation recommends using curl_global_init() at the beginning of the program to set up the necessary environment for curl operations. See "Global preparation" section:
    - https://curl.se/libcurl/c/libcurl-tutorial.html
  2. Callback prototype mismatch:
    The prototype for the callback function seems to be inconsistent with the one documented on the official libcurl site. The prototype for this callback function is described here:
    - https://curl.se/libcurl/c/CURLOPT_WRITEFUNCTION.html
size_t write_callback(char *ptr, size_t size, size_t nmemb, void *userdata);

On a related note, I've created a more detailed setup documentation and added a simple example as well as a slightly more complex one that includes POST requests, which some may find useful:
- https://github.com/voidlib/cpp-curl-example

Thanks again for your contribution—it was a great starting point for me!

Best regards,
@voiduin

@SiddhanthMateDEV
Copy link

this was the best explanation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment