这两天在用libcurl发送http请求
代码写好了,联调时发现服务器老是返回“Unsupported Media Type”这个错误,不支持的媒体类型,百度谷歌了一圈遇见这个问题的不少,但是大多数没有把解决方案发出来。
其实很简单,如果能认真把curl的example例程看清楚就不会出现这样的问题。
下面把代码发出来,供后来者参考
帖子请看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();//对curl进行初始化 if(curl){ curl_easy_setopt(curl, CURLOPT_URL, url); //设置下载地址 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_TIMEOUT, CURL_TIMEOUT);//设置超时时间 curl_easy_setopt(curl, CURLOPT_POST, 1L);//设置超时时间 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postdata);//设置超时时间 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, func);//设置写数据的函数 curl_easy_setopt(curl, CURLOPT_WRITEDATA, data);//设置写数据的变量 res = curl_easy_perform(curl);//执行下载 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; } }
其实错误就错在了curl_slist_append函数的使用上,这个函数的返回值是必须指向headers的,说实话看起来很变态,参数已经包含这个了,为什么还要返回值这样做!
libcurl官网上对这个api是这样描述的
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 while the new list is returned from this function.
The specified string has been appended when this function returns. curl_slist_append() copies the string.
The list should be freed again (after usage) with curl_slist_free_all.
RETURN VALUE
A null pointer is returned if anything went wrong, otherwise the new list pointer is returned.
看上面的红色字体,其实说的还是不够清晰!