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;}


本文链接http://www.taodudu.cc/news/show-647462.html