These two days are sending HTTP requests with Libcurl
The code is written, the unsupported found that the server always return to the "media type" error, not supported by the medium type, Baidu Google a lap to meet the problem of many, but most did not send out the solution.
In fact, it is very simple, if you can seriously example curl of the routine to see clearly there will not be such a problem.
The following code is sent out for later reference
Post please see http://bbs.csdn.net/topics/390973641
int curl_post_res (const char*postdata,const char *url,cb_func func,void *data) {Curlcode res = 0; Char tmp[32]={0}; CURL *curl=null; struct Curl_slist *headers = NULL; if (!data) return-1; if (!url) return-1; Jdebug (Debug_state, "url:%s\n", url); snprintf (tmp,sizeof (TMP), "Content-length:%d", strlen (PostData)); Jdebug (Debug_state, "tmp=%s\n", TMP); headers = curl_slist_append (headers, "Accept:application/json"); headers = curl_slist_append (headers, "Content-type:application/json"); headers = curl_slist_append (headers, "charset:utf-8"); headers = curl_slist_append (headers, TMP); Curl = Curl_easy_init ();//Initialize curl if (curl) {curl_easy_setopt (curl, Curlopt_url, URL);//Set curl_easy_s Etopt (Curl, Curlopt_httpheader, headers); Curl_easy_setopt (Curl, curlopt_timeout, curl_timeout);//Set timeout time curl_easy_setopt (curl, Curlopt_post, 1L);//Set timeout Curl_easy_setopt (Curl, Curlopt_postfields, postdata);//Set timeoutCurl_easy_setopt (Curl, Curlopt_writefunction, func);//Set the function to write data curl_easy_setopt (curl, Curlopt_writedata, D ATA);//Set the variable to write data res = curl_easy_perform (curl);//Perform download jdebug (debug_state, "Curl perform is ok!\n"); Curl_easy_cleanup (curl); Curl_slist_free_all (headers); return res; }else{Jdebug (Debug_err, "Curl Easy init is err!\n"); Curl_slist_free_all (headers); Return-2; } }
In fact, the error is wrong in the use of the Curl_slist_append function, the return value of this function must point to headers, to tell the truth looks very perverted, the parameters already contain this, why also return the value to do so!
This API is described by the Libcurl website
NAME
Curl_slist_append-add a string to an slist
Synopsis
#include <curl/curl.h>
struct curl_slist *curl_slist_append (struct curl_slist * list, const char * string);
DESCRIPTION
Curl_slist_append () appends a specified string to a linked list of strings. The existing list should be passed as the first argument and the new list is returned from this function. The specified string has been appended if this function returns. Curl_slist_append () copies the string.
The list should is freed again (after usage) with Curl_slist_free_all.
RETURN VALUE
A NULL pointer is returned if anything went wrong, and otherwise the new list pointer is returned.
Look at the red font above, actually said is not clear enough!
Unsupported Media Type
C language Libcurl POST JSON string Error "Unsupported Media Type"