我使用了curl帮助中的示例代码,但服务器接收空对象和null自定义标头。 GET方法工作正常。 strbuf.GetString()
- 它是转换为String的json对象。
CURL *curl;
CURLcode res;
struct WriteThis pooh;
res = curl_global_init(CURL_GLOBAL_DEFAULT);
struct curl_slist *headers=NULL;
curl_slist_append(headers, "Accept: application/json");
curl_slist_append( headers, "Content-Type: application/json");
curl_slist_append( headers, "charsets: utf-8");
curl_slist_append( headers, "AuthToken: 9BA1B05482567E64037573FFB68672DCB52E4993");
curl = curl_easy_init();
if (curl)
{
pooh.readptr = strbuf.GetString();
pooh.sizeleft = (long)strlen(strbuf.GetString());
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_POST, 1L);
curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback);
curl_easy_setopt(curl, CURLOPT_READDATA, &pooh);
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,writer);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, &pooh);
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, pooh.sizeleft);
res = curl_easy_perform(curl);
if (CURLE_OK == res)
{
char *ct;
res = curl_easy_getinfo(curl, CURLINFO_CONTENT_TYPE, &ct);
if((CURLE_OK == res) && ct){
}
}
curl_easy_cleanup(curl);
}
curl_global_cleanup();
struct WriteThis {
const char *readptr;
long sizeleft;
};
static size_t read_callback(void *ptr, size_t size, size_t nmemb, void *userp)
{
struct WriteThis *pooh = (struct WriteThis *)userp;
if(size*nmemb < 1)
return 0;
if(pooh->sizeleft) {
*(char *)ptr = pooh->readptr[0]; /* copy one single byte */
pooh->readptr++; /* advance pointer */
pooh->sizeleft--; /* less data left */
return 1; /* we return 1 byte at a time! */
}
return 0; /* no more data left to deliver */
}
答案 0 :(得分:1)
相反:
struct curl_slist *headers = NULL;
curl_slist_append(headers, "Accept: application/json");
curl_slist_append(headers, "Content-Type: application/json");
curl_slist_append(headers, "charsets: utf-8");
curl_slist_append(headers, "AuthToken: 9BA1B05482567E64037573FFB68672DCB52E4993");
curl = curl_easy_init();
此:
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, "Accept: application/json");
headers = curl_slist_append(headers, "Content-Type: application/json");
headers = curl_slist_append(headers, "charsets: utf-8");
headers = curl_slist_append(headers, "AuthToken: 9BA1B05482567E64037573FFB68672DCB52E4993");
curl = curl_easy_init();
答案 1 :(得分:0)
您将两者设置为读回调和CURLOPT_POSTFIELDS
。那没用。您需要决定要提供数据的方式。在这种情况下,我相信它会使用POSTFIELDS并忽略读取回调。
传递给CURLOPT_POSTFIELDS
的指针不是字符串,因此libcurl会从那里发送有趣的二进制“垃圾”。您可能希望在那里传递pooh.readptr
。