转载:http://blog.csdn.net/dgyanyong/article/details/14166217

转载:http://blog.csdn.net/th_gsb/article/details/42810007

转载:http://www.cnblogs.com/yangxunpeng/articles/7040697.html

转载:http://blog.csdn.net/wzx19840423/article/details/6587370

第一步:建立控制台工程,配置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 <iostream>
#include <sstream>
//json
#include "json\json.h"
using namespace std; //http://blog.csdn.net/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);
return ret_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);
return ret_str;
} string AsciiToUtf8(const string& str)
{
return UnicodeToUtf8(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 << endl; return size * nmemb;
}

方式一:用JsonCpp构建Json串
//POST json
int main()
{
CURL *curl;
CURLcode res;
char tmp_str[256] = { 0 };
std::stringstream out; //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
int main()
{
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::stringstream out; //设置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

libcurl HTTP POST请求向服务器发送json数据【转】的更多相关文章

  1. libcurl HTTP POST请求向服务器发送json数据

    转载:http://blog.csdn.net/dgyanyong/article/details/14166217 转载:http://blog.csdn.net/th_gsb/article/de ...

  2. (九)springmvc之json的数据请求(客户端发送json数据到服务端)

    index.jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pag ...

  3. curl向web服务器发送json数据

    c++使用libcurl: /* *g++ demo.cpp -g -Wall -lcurl */ #include <string.h> #include <stdlib.h> ...

  4. iOS开发网络篇—发送json数据给服务器以及多值参数

    iOS开发网络篇—发送json数据给服务器以及多值参数 一.发送JSON数据给服务器 发送JSON数据给服务器的步骤: (1)一定要使用POST请求 (2)设置请求头 (3)设置JSON数据为请求体 ...

  5. 【转】iOS开发网络篇—发送json数据给服务器以及多值参数

    原文: http://www.cnblogs.com/wendingding/p/3950132.html 一.发送JSON数据给服务器 发送JSON数据给服务器的步骤: (1)一定要使用POST请求 ...

  6. IOS-网络(发送JSON数据给服务器和多值参数)

    三步走: 1.使用POST请求 2.设置请求头 [request setValue:@"application/json" forHTTPHeaderField:@"Co ...

  7. SpringMVC客户端发送json数据时报400错误

    当测试客户端发送json数据给服务器时,找不到响应路径? 原来是参数类型不符,即使是json也要考虑参数的个数和类型 解决:将age请求参数由"udf"改为"3" ...

  8. python 全栈开发,Day75(Django与Ajax,文件上传,ajax发送json数据,基于Ajax的文件上传,SweetAlert插件)

    昨日内容回顾 基于对象的跨表查询 正向查询:关联属性在A表中,所以A对象找关联B表数据,正向查询 反向查询:关联属性在A表中,所以B对象找A对象,反向查询 一对多: 按字段:xx book ----- ...

  9. Django与Ajax,文件上传,ajax发送json数据,基于Ajax的文件上传,SweetAlert插件

    一.Django与Ajax AJAX准备知识:JSON 什么是 JSON ? JSON 指的是 JavaScript 对象表示法(JavaScript Object Notation) JSON 是轻 ...

随机推荐

  1. NOI.AC NOIP模拟赛 第三场 补记

    NOI.AC NOIP模拟赛 第三场 补记 列队 题目大意: 给定一个\(n\times m(n,m\le1000)\)的矩阵,每个格子上有一个数\(w_{i,j}\).保证\(w_{i,j}\)互不 ...

  2. node-webkit开发桌面应用

    Node-Webkit能够做什么呢?(打开链接看discuss) github 项目源:https://github.com/rogerwang 导言 node-webkit 是一个很神奇的桌面客户端 ...

  3. Codeforces Round #369 (Div. 2) A. Bus to Udayland 水题

    A. Bus to Udayland 题目连接: http://www.codeforces.com/contest/711/problem/A Description ZS the Coder an ...

  4. 单源最短路模板 + hdu - 2544

    Floyd Floyd 本质上类似一种动态规划,dp [ i ] [ j ] = dp [ i ] [ k ] + dp[ k ] [ j ]. /** * Night gathers, and no ...

  5. 理解JVM模型

    概括 JVM运行时数据区可以划分为5部分,分别是:程序计数器.虚拟机栈.本地方法栈.堆.方法区 程序计数器(Program Counter Register) 相当于当前线程所执行字节码的行号指示器. ...

  6. dubbox REST服务使用fastjson替换jackson

    上一节讲解了resteasy如何使用fastjson来替换默认的jackson,虽然dubbox内部采用的就是resteasy,但是大多数情况下,dubbox服务是一个独立的app,并不需要以war包 ...

  7. STM32F1-workarea : how to drive a WS2812 RGB LED using PWM and DMA

    how to drive a WS2812 RGB LED using PWM and DMA #include <stm32f10x.h> void Delay(__IO uint32_ ...

  8. VMware Workstation Pro 12 桥接联网(物理主机:Windows 7,虚拟机:CentOS 6.8)

    物理主机:Windows 7,虚拟机:CentOS 6.8 1.设置虚拟机的 默认路径:编辑 -> 首选项 -> 设置“虚拟机的默认位置” 2.设置 虚拟网络:编辑 -> 虚拟网络编 ...

  9. [DLX反复覆盖] hdu 3656 Fire station

    题意: N个点.再点上建M个消防站. 问消防站到每一个点的最大距离的最小是多少. 思路: DLX直接二分推断TLE了. 这时候一个非常巧妙的思路 我们求的距离一定是两个点之间的距离 因此我们把距离都求 ...

  10. 采用模拟账号读取Exchange server未读邮件的注意事项(链接邮箱问题)【转】

    最近做项目碰到Exchange中,用EWS API方法读取的未读邮箱(ConnectingIdType.PrincipalName设置该属性的方法)附带代码部分: 核心代码 using Microso ...