json libcurld 构造_libcurl HTTP POST请求向服务器发送json数据

这篇博客介绍了如何利用libcurl库在C++中构造HTTP POST请求,将JSON数据发送到服务器。首先,配置libcurl静态链接库,然后引入JsonCpp库处理JSON。接着,通过示例展示了两种构建和发送JSON的方法:一是用JsonCpp构建Json串,二是手动拼接Json串。在发送过程中涉及了ASCII到Unicode再到UTF-8的编码转换。最后,讨论了JSON字符串编码问题和遇到的错误。

第一步:建立控制台工程,配置libcurl

在stdafx.h中导入引用的libcurl库,在用的是静态链接

.......#define CURL_STATICLIB#include"curl\curl.h"#ifdef _DEBUG#pragma comment(lib,"libcurld.lib")

#else

#pragma comment(lib,"libcurl.lib")

#endif

#pragma comment ( lib, "ws2_32.lib" )

#pragma comment ( lib, "winmm.lib" )

#pragma comment ( lib, "wldap32.lib" )

#pragma comment(lib, "Advapi32.lib")........

库文件的位置

第二步:配置JsonCpp库,如果想在工程中直接引用源码,请参考我之前的博客

第三步:上传json串

#include "stdafx.h"#include#include

//json

#include "json\json.h"

using namespacestd;//http://blog.youkuaiyun.com/wyansai/article/details/50764315

wstring AsciiToUnicode(const string&str)

{//预算-缓冲区中宽字节的长度

int unicodeLen = MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, nullptr, 0);//给指向缓冲区的指针变量分配内存

wchar_t *pUnicode = (wchar_t*)malloc(sizeof(wchar_t)*unicodeLen);//开始向缓冲区转换字节

MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, pUnicode, unicodeLen);

wstring ret_str=pUnicode;free(pUnicode);returnret_str;

}string UnicodeToUtf8(const wstring&wstr)

{//预算-缓冲区中多字节的长度

int ansiiLen = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, nullptr, 0, nullptr, nullptr);//给指向缓冲区的指针变量分配内存

char *pAssii = (char*)malloc(sizeof(char)*ansiiLen);//开始向缓冲区转换字节

WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, pAssii, ansiiLen, nullptr, nullptr);string ret_str =pAssii;free(pAssii);returnret_str;

}string AsciiToUtf8(const string&str)

{returnUnicodeToUtf8(AsciiToUnicode(str));

}//回调函数

size_t write_data(void *ptr, size_t size, size_t nmemb, void *stream)

{string data((const char*) ptr, (size_t) size *nmemb);*((stringstream*) stream) << data <

}

方式一:用JsonCpp构建Json串//POST json

intmain()

{

CURL*curl;

CURLcode res;char tmp_str[256] = { 0};

std::stringstreamout;//HTTP报文头

struct curl_slist* headers =NULL;char *url = "http://if.qdocument.net:705/bic/operationNote/upload";

curl=curl_easy_init();if(curl)

{//构建json

Json::Value item;

item["uid"]=Json::Value("chechenluoyang@163.com");

item["fileName"]=Json::Value("梅西&内马尔&苏亚雷斯.txt");

item["time"]=Json::Value("2017.07.31 9:55:22");

item["type"]=Json::Value("Libcurl HTTP POST Json串");

item["authList"]=Json::Value("weidong0925@126.com");

std::string jsonout =item.toStyledString();

jsonout=AsciiToUtf8(jsonout);//设置url

curl_easy_setopt(curl, CURLOPT_URL, url);//设置http发送的内容类型为JSON//构建HTTP报文头

sprintf_s(tmp_str, "Content-Length: %s", jsonout.c_str());

headers=curl_slist_append(headers, "Content-Type:application/json;charset=UTF-8");//headers=curl_slist_append(headers, tmp_str);//在请求头中设置长度,请求会失败,还没找到原因

curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);//curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");//自定义请求方式

curl_easy_setopt(curl, CURLOPT_POST, 1);//设置为非0表示本次操作为POST//设置要POST的JSON数据

curl_easy_setopt(curl, CURLOPT_POSTFIELDS, jsonout.c_str());curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, jsonout.size());//设置上传json串长度,这个设置可以忽略//设置接收数据的处理函数和存放变量

curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);//设置回调函数

curl_easy_setopt(curl, CURLOPT_WRITEDATA, &out);//设置写数据

res = curl_easy_perform(curl);//执行

curl_slist_free_all(headers); /* free the list again */

string str_json = out.str();//返回请求值

printf("%s",str_json.c_str());/*always cleanup*/curl_easy_cleanup(curl);

}return 0;

}

方式二:手动拼Json串

//POST json

intmain()

{

CURL*curl;

CURLcode res;char szJsonData[1024];//HTTP报文头

struct curl_slist* headers =NULL;char *url = "http://if.qdocument.net:705/bic/operationNote/upload";

curl=curl_easy_init();if(curl)

{//string类型的json串

memset(szJsonData, 0, sizeof(szJsonData));

std::string strJson = "{";

strJson+= "\"uid\" : \"chechenluoyang@163.com\",";

strJson+= "\"fileName\" : \"梅西.txt\",";

strJson+= "\"time\" : \"2017.07.28 10:55:22\",";

strJson+= "\"type\" : \"Libcurl HTTP POST JSON \",";

strJson+= "\"authList\" : \"123\"";

strJson+= "}";

strcpy(szJsonData, strJson.c_str());

strJson= string AsciiToUtf8(strJson);//如果json串中包含有中文,必须进行转码

std::wstring wstrJson= _T("{");

wstrJson+= _T("\"uid\" : \"chechenluoyang@163.com\",");

wstrJson+= _T("\"fileName\" : \"梅西.txt\",");

wstrJson+= _T("\"time\" : \"2017.07.29 10:55:22\",");

wstrJson+= _T("\"type\" : \"Libcurl HTTP POST JSON \",");

wstrJson+= _T("\"authList\" : \"test\"");

wstrJson+= _T("}");string testJson =UnicodeToUtf8(wstrJson);

std::stringstreamout;//设置url

curl_easy_setopt(curl, CURLOPT_URL, url);//设置http发送的内容类型为JSON//构建HTTP报文头

headers=curl_slist_append(headers, "Content-Type:application/json;charset=UTF-8");

curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);//curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");

curl_easy_setopt(curl, CURLOPT_POST, 1);//设置为非0表示本次操作为POST//设置要POST的JSON数据 //curl_easy_setopt(curl, CURLOPT_POSTFIELDS, testJson.c_str());//以多字节上传

curl_easy_setopt(curl, CURLOPT_POSTFIELDS, testJson.c_str());//以Unicode编码上传//curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, strJson.size());//设置接收数据的处理函数和存放变量

curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);//设置回调函数

curl_easy_setopt(curl, CURLOPT_WRITEDATA, &out);//设置写数据

res=curl_easy_perform(curl);

curl_slist_free_all(headers); /* free the list again */

string str_json = out.str();//返回值 例如:{"status":"ok"} printf("%s",str_json.c_str());/*always cleanup*/curl_easy_cleanup(curl);

}return 0;

}

后记:上传的Json串,必须以UTF-8的方式上传,因为服务器端是以UTF-8进行编码显示,按说发送过去的Json中中文显示乱码,但用libcurl库直接请求失败,还有就是我在手动拼Json串是格式错误,它们都会返回"客户端发送的请求在语法上不正确"

在解决这个问题过程中,想到一个思路,让源码文件的编码为UTF-8,然后直接上传含有中文的json(不进行编码转换),发现还是不行。

以string类型保存的json,编码转换流程:  Ascii--->Unicode--->UTF-8

以wstring类型保存的json,编码转换流程:Unicode--->UTF-8

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值