libcurl发送post方式的json串出现“Unsupported Media Type”解决办法

libcurl发送post方式的json串出现“Unsupported Media Type”
本帖最后由 jk110333 于 2015-01-19 09:33:09 编辑
我在使用C语言libcurl发送json串,使用post方式,但是接收到服务器的回复是
<html><head><title>Error</title></head><body>Unsupported Media Type</body></html>

开始怀疑是服务器的问题,然后用了curl命令模拟发送,结果出现下面的情况。
加上-H  "Content-Type: application/json"参数就没问题了,确定是我这边的问题。如下
jack@ubuntu:~$ curl -X POST  -d '{"test":1}'  http://192.168.0.105:8080/WorkerInformation/router/test                              
<html><head><title>Error</title></head><body>Unsupported Media Type</body></html>

jack@ubuntu:~$ curl -X POST  -d '{"test":1}' -H "Content-Type: application/json" http://192.168.0.105:8080/WorkerInformation/router/test
{"result":"OK"}
jack@ubuntu:~$ 


于是我在代码中加入如下代码,大概是这样,代码不在身边,明天送上
#include <>
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);
    curl_slist_append(headers, "Accept: application/json");
    curl_slist_append(headers, "Content-Type: application/json");
    curl_slist_append(headers, "charset: utf-8");
    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; 
    }
}
}

------解决思路----------------------
1、HTTP头部不是这么加的,应该是这样:

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);

2、遇到这种问题你先抓包看一下你发出去的是什么样的包,用HttpAnalyzer就可以。