C++使用CURL库POST请求向服务器发送JSON数据

具体测试代码见:

https://pan.baidu.com/s/1d4UXxMb_TwP6C8X1ZeGOlA,提取码:yg2j

1.准备工作

      curl库和json库打导入,添加附加包含目录是include目录,添加预处理定义,添加外部依赖项

2.代码实现

// resful.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"

#include <stdio.h>
#include <iostream>
#include <Windows.h>
#include <stdlib.h>
#include <sys/types.h>
#include <http.h>
#include "stdafx.h"
#include <iostream>
#include <sstream>
#include "json\json.h"
#include "curl\curl.h"
using namespace std;
//#pragma comment(lib, "libcurl.lib")
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);

    *((std::stringstream*) stream) << data << endl;

    return size * nmemb;
}
int _tmain(int argc, _TCHAR* argv[])
{
	CURL* curl = NULL;
	CURLcode res = CURLE_OK;
	//HTTP报文头
	struct curl_slist* headers = NULL;
	
 
	Json::Value value;
    value["dst_uid"]=Json::Value("wZdxqE9zZUlSrB");
	value["item_uid"]=Json::Value("AqRxqE9zZUlSrB");
	value["txt_lines"]=Json::Value("YWJjZGVmPXNzcyZhYmNkZWbI1cbaPTIwMTktMDQtMTM=");
    Json::Reader reader;
		
    std::string strResult = value.toStyledString();
	strResult = AsciiToUtf8(strResult);
    Json::Value result;
    //测试构造字符串内容
    /*if (reader.parse(strResult,result))
    {
            if(!result["dst_uid"].isNull())
            {
                    cout<<result["id"].asInt()<<std::endl;
            }
    }*/
    std::cout<<value.toStyledString().c_str()<<std::endl;
  /*这个函数只能用一次,如果这个函数在curl_easy_init函数调用时还没调用,
  它讲由libcurl库自动调用,所以多线程下最好在主线程中调用一次该函数以防止在线程
  中curl_easy_init时多次调用*/
  curl_global_init(CURL_GLOBAL_ALL);
  //初始化easy handler句柄
  curl = curl_easy_init();
  if (curl) {
    //构建HTTP报文头
    curl_slist *http_headers = NULL;
    http_headers = curl_slist_append(http_headers, "Accept: application/json");
    http_headers = curl_slist_append(http_headers, "Content-Type: application/json");//text/html
    http_headers = curl_slist_append(http_headers, "charsets: utf-8");
	//设置method为post
	//curl_easy_setopt(m_pCurlHandlder, CURLOPT_POST, 1);
    curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
	//设置post请求的url地址
    curl_easy_setopt(curl, CURLOPT_URL, "http://localhost:8080/Pub_Service/signer/do");
	//设置HTTP头
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, http_headers);
	//设置发送超时时间
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, 1);
 
    curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
	//执行单条请求
	curl_easy_setopt(curl,CURLOPT_POSTFIELDS,strResult.c_str());
	//curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, value.toStyledString().size());
	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);//设置回调函数
    res = curl_easy_perform(curl);
    if (res != CURLE_OK) {
	  //curl_easy_strerror进行出错打印
      cout << "curl_easy_perform() failed:" << curl_easy_strerror(res);
    }
    curl_slist_free_all(headers);
	//这个调用用来结束一个会话.与curl_easy_init配合着用
    curl_easy_cleanup(curl);
	//在结束libcurl使用的时候,用来对curl_global_init做的工作清理。类似于close的函数
	curl_global_cleanup();
	return 0;
	}

}
发布了9 篇原创文章 · 获赞 8 · 访问量 9508

猜你喜欢

转载自blog.csdn.net/qq_41482046/article/details/93379733