1. 程式人生 > >C++ 訪問http介面

C++ 訪問http介面

新增標頭檔案#include <wininet.h>

附加庫:#pragma comment(lib,"Wininet.lib")

// 傳送
int GetURLInternal(LPCSTR lpszUrl, std::string& content)
{
	int result = -1;
	HINTERNET hSession = InternetOpenA(NULL,	INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
	if (NULL != hSession)
	{
		HINTERNET hHttp = InternetOpenUrlA(hSession,	lpszUrl, NULL, 0, 
			INTERNET_FLAG_DONT_CACHE|INTERNET_FLAG_RELOAD|INTERNET_FLAG_NO_CACHE_WRITE, 0);
		if (NULL != hHttp)
		{
			DWORD num = 0;
			const DWORD BUFFER_SIZE = 8192;
			char buffer[BUFFER_SIZE];
			do
			{
				if(InternetReadFile(hHttp, buffer, BUFFER_SIZE, &num))
				{
					content.append(buffer, num);
					result = 0;
				}
			} while (num > 0);
			InternetCloseHandle(hHttp);
			hHttp = NULL;
		}

		InternetCloseHandle(hSession);
		hSession = NULL;
	}
	return result;
}

// 中文要進行URL編碼
std::string urlencode(std::string &str_source)  
{  
	char const *in_str = str_source.c_str();  
	int in_str_len = strlen(in_str);  
	int out_str_len = 0;  
	std::string out_str;  
	register unsigned char c;  
	unsigned char *to, *start;  
	unsigned char const *from, *end;  
	unsigned char hexchars[] = "0123456789ABCDEF";  

	from = (unsigned char *)in_str;  
	end = (unsigned char *)in_str + in_str_len;  
	start = to = (unsigned char *) malloc(3*in_str_len+1);  

	while (from < end) {  
		c = *from++;  

		if (c == ' ') {  
			*to++ = '+';  
		} else if ((c < '0' && c != '-' && c != '.') ||  
			(c < 'A' && c > '9') ||  
			(c > 'Z' && c < 'a' && c != '_') ||  
			(c > 'z')) {   
				to[0] = '%';  
				to[1] = hexchars[c >> 4];  
				to[2] = hexchars[c & 15];  
				to += 3;  
		} else {  
			*to++ = c;  
		}  
	}  
	*to = 0;  

	out_str_len = to - start;  
	out_str = (char *) start;  
	free(start);  
	return out_str;  
}  

// 得到post的字串
int SendSMSCU(std::string strTelNum, std::string strSMSText){std::string strSmsRequest; // 請求std::string strSmsResponse; // 結果strSmsRequest = "http://js.ums86.com:8899/sms/Api/Send.do?SpCode=205395&LoginName=cs_rlzy&Password=csinfo2011&MessageContent=";strSmsRequest += urlencode(strSMSText);strSmsRequest += "&UserNumber=";strSmsRequest += strTelNum;strSmsRequest +="&SerialNumber=01234567890123456789&ScheduleTime=&f=1";GetURLInternal(strSmsRequest.c_str(), strSmsResponse);return 0;}