Want to send Http_post request in C + +, use Libcurl.
Want to wrap it, because the default HTTP response results are printed to stdout, if you want to deal with the results of the response, you need to define a callback function.
Considering that we want to wrap the functionality, a callback function is not very good to put on the outside, so consider using a lambda expression.
Here are the forms you can use:
1#include <stdio.h>2#include <curl/curl.h>3#include <iostream>4 5 using namespacestd;6 7 stringHttp_post (stringUrlstringpostdata) {8CURL *Curl;9 Curlcode Res;Ten stringresult; Onetypedef size_t (*curl_write_callback) (Char*buffer, size_t size, Asize_t Nitems,string*outstream); - -Auto writer = [] (Char* buffer,size_t size,size_t Nitems,string*OutStream) the-size_t { - if(outstream==NULL) - { - return 0; + } -Outstream->append (buffer,size*nitems); + returnsize*Nitems; A }; at - Curl_global_init (curl_global_all); - -Curl =curl_easy_init (); - if(Curl) { - curl_easy_setopt (Curl, Curlopt_url, url.c_str ()); in curl_easy_setopt (Curl, Curlopt_postfields, postdata.c_str ()); - curl_easy_setopt (Curl, curlopt_writefunction, to (Curl_write_callback) writer); +Curl_easy_setopt (Curl, Curlopt_writedata, &result); -res =curl_easy_perform (curl); the if(Res! =CURLE_OK) *fprintf (stderr,"Curl_easy_perform () failed:%s\n", $ Curl_easy_strerror (res));Panax Notoginseng curl_easy_cleanup (curl); - } the //cout << "buffer:" << result << Endl; + Curl_global_cleanup (); A returnresult; the}
Notice that we do a coercion type conversion when we use writer as an argument. Without this coercion type conversion, the program exits and returns-1
C + + takes lambda as a callback function