1. 程式人生 > >C++ 使用post/get進行傳送資料

C++ 使用post/get進行傳送資料

使用開源的libcur實現post傳送資料。libcur的使用請自行百度。下面是我的程式碼,用post傳送過個型別的資料

注意:程式碼不能直接使用,因為我裡面依賴了其他檔案和類,這裡這是做一個示例

//httpcurl.h
#include <string>
#include "SqlOperation.h"

class  CFaceRecognice;

class CHttpClient
{
public:
	CHttpClient(CSqlOperation* sqloperate);
	~CHttpClient(void);

public:
	int Post(const std::string strUrl, int found_int, string guid_str, BYTE* feat_byte, BYTE* photo_byte, long picsize);
	
private:
	bool m_bDebug;
	CSqlOperation* m_sqloperate;
};

//httpcurl.cpp 
#include "stdafx.h"
#include "httpcurl.h"
#include "curl.h"
#include "json/json.h"

CHttpClient::CHttpClient(CSqlOperation* sqloperate)   //CSqlOperation 是我其他類中自己定義的一個類,可以不傳入
:m_bDebug(false)
,m_sqloperate(sqloperate)
{

}

CHttpClient::~CHttpClient(void)
{

}

string Utf82Ansi(const char* utf8)
{

	int WLength = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, NULL);
	LPWSTR pszW = (LPWSTR)_alloca((WLength + 1) *sizeof(WCHAR));
	MultiByteToWideChar(CP_UTF8, 0, utf8, -1, pszW, WLength);
	pszW[WLength] = 0;

	int ALength = WideCharToMultiByte(CP_ACP, 0, pszW, -1, NULL, 0, NULL, NULL);
	LPSTR pszA = (LPSTR)_alloca(ALength + 1);
	WideCharToMultiByte(CP_ACP, 0, pszW, -1, pszA, ALength, NULL, NULL);
	pszA[ALength] = 0;
	return pszA;
}


//post返回呼叫的函式,如果沒定義此函式則會有一個預設的函式
//如果需要給OnWriteData傳遞指標,則傳遞給lpVoid
void OnWriteData(void* buffer, size_t size, size_t nmemb, void* lpVoid)
{

	if (NULL == buffer)
	{
		return;
	}

	Json::Reader reader;
	Json::Value json_value;
	if (reader.parse((char*)buffer, json_value))  // reader將Json字串解析到root,root將包含Json裡所有子元素  
	{
		if (!json_value["found_c"].isNull())
		{
			int face_found = json_value["found_c"].asInt();
			if (!face_found) //客戶端資料庫中沒有找到face資訊,認為是新人
			{
				if (!json_value["guid_c"].isNull() && !json_value["guid_s"].isNull())
				{
					string guid_c = Utf82Ansi(json_value["guid_c"].asString().c_str());
					string guid_s = Utf82Ansi(json_value["guid_s"].asString().c_str());
					if (strcmp(guid_c.c_str(), guid_s.c_str()) != 0)
					{
  						CSqlOperation* sql = (CSqlOperation*)lpVoid;
  						sql->UpdateGUID(guid_c, guid_s);    //此處更新資料庫
					}
				}
			}
		}		
	}
	return;
}



char* Unicode2Utf8(const TCHAR* unicode)
{
	int len;
	len = WideCharToMultiByte(CP_UTF8, 0, (const wchar_t*)unicode, -1, NULL, 0, NULL, NULL);
	char *szUtf8 = (char*)malloc(len + 1);
	memset(szUtf8, 0, len + 1);
	WideCharToMultiByte(CP_UTF8, 0, (const wchar_t*)unicode, -1, szUtf8, len, NULL, NULL);
	return (char*)szUtf8;
}

BOOL StringToWString0(const std::string &str, std::wstring &wstr)
{
	int nLen = (int)str.length();
	wstr.resize(nLen, L' ');

	int nResult = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)str.c_str(), nLen, (LPWSTR)wstr.c_str(), nLen);

	if (nResult == 0)
	{
		return FALSE;
	}

	return TRUE;
}
/*
  post傳送了三種類型的資料

  found:整形資料
  guid:字元型資料
  feat:二進位制位元組流資料
  photo:二進位制位元組流資料,其實是一個圖片
*/

int CHttpClient::Post(const std::string strUrl, int found_int, string guid_str, BYTE* feat_byte, BYTE* photo_byte,long picsize)
{
	CURLcode res;

	struct curl_httppost *formpost = NULL;
	struct curl_httppost *lastptr = NULL;

	CURL* curl = curl_easy_init();
	if (NULL == curl)
	{
		return CURLE_FAILED_INIT;
	}

	if (found_int)
	{
		curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, Unicode2Utf8(_T("found")), CURLFORM_COPYCONTENTS, "1", CURLFORM_END);
	}
	else
	{
		curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, Unicode2Utf8(_T("found")), CURLFORM_COPYCONTENTS, "0", CURLFORM_END);
	}
	
	
	wstring wguid;

	StringToWString0(guid_str, wguid);

	curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, Unicode2Utf8(_T("guid")), CURLFORM_COPYCONTENTS, Unicode2Utf8(wguid.c_str()), CURLFORM_END);
	
	curl_formadd(&formpost, &lastptr,
		CURLFORM_COPYNAME, Unicode2Utf8(_T("feat")),
		CURLFORM_BUFFER, "data",
		CURLFORM_BUFFERPTR, feat_byte,
		CURLFORM_BUFFERLENGTH, sizeof(float)*2048,
		CURLFORM_END);

	curl_formadd(&formpost, &lastptr,
		CURLFORM_COPYNAME, Unicode2Utf8(_T("photo")),
		CURLFORM_BUFFER, "data",
		CURLFORM_BUFFERPTR, photo_byte,
		CURLFORM_BUFFERLENGTH, sizeof(float)* 2048,
		CURLFORM_END);
	string url = "http://127.0.0.1:8080/apiReport.do"; //這是我的url地址,根據自己的需求做更改


	struct curl_slist *headers = NULL;
	//設定post的一些相關資訊
	headers = curl_slist_append(headers, "POST");
	headers = curl_slist_append(headers, "Connection: Keep-Alive");
	headers = curl_slist_append(headers, "Accept: */*");
	headers = curl_slist_append(headers, "Content-Type: multipart/form-data;");

	curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
	curl_easy_setopt(curl, CURLOPT_URL, url.c_str());

	curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);


  	curl_easy_setopt(curl, CURLOPT_READFUNCTION, NULL);
  	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, OnWriteData);
 	curl_easy_setopt(curl, CURLOPT_WRITEDATA, m_sqloperate); //給OnWriteData傳遞的指標引數
	res = curl_easy_perform(curl);
	curl_formfree(formpost);
	curl_easy_cleanup(curl);
	return res;
}