欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c++发送http请求chttpcile代码实例

程序员文章站 2022-05-23 09:48:33
直接贴代码 但是发送中文时 是gb2312的url编码不是utf-8的 /** * \brief 对url特殊字符进行编码 * \param s 输入字符串...

直接贴代码 但是发送中文时 是gb2312的url编码不是utf-8的

/** 
 * \brief 对url特殊字符进行编码 
 * \param s 输入字符串 
 * \param len 输入字符串长度 
 * \param new_length 输出字符串长度 
 * \return 输出编码后的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;  
}  
std::string urlpost(std::string &str_source)  
{  
    char *a = "data=";
	std::string str = std::string(a) + urlencode(str_source);
    return str;  
}  
CString http_request(CString server, CString uri,int port,CHAR* strFormData){
	//设置session
	CInternetSession session(_T("My Session")); 
	CHttpConnection* pServer = NULL;
	CHttpFile* pFile = NULL;
	//设置报头
	CString szHeaders( "Content-Type: application/x-www-form-urlencoded;");
	CString strObject(uri); 
	CString out;
	DWORD dwRet;


char *szBuff = new char[];
memset(szBuff, 0, sizeof(szBuff));

try
{

    CString strServerName(server);
   INTERNET_PORT nPort(port);

   pServer = session.GetHttpConnection(strServerName, nPort);
   //设置发送类型
   pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_POST, strObject);
   //设置报头
   pFile->AddRequestHeaders(szHeaders);
   //发送请求
   pFile->SendRequest(szHeaders, szHeaders.GetLength(),(LPVOID)strFormData, strlen(strFormData));
   //获取服务端返回数据
   pFile->QueryInfoStatusCode(dwRet);
   //读取返回数据
   if (dwRet == HTTP_STATUS_OK)
   {
       UINT nRead = pFile->Read(szBuff, sizeof(szBuff));
       //while (nRead > 0)
       //{
           out = CString(szBuff);
       //}
   } else {
        out = CString("Communication error!");
   }
   //删除file
   delete pFile;
   //关闭服务
   pServer->Close()
	//删除服务;
   delete pServer;
}
catch (CInternetException* pEx)
{
    //catch errors from WinInet

    out = CString("Network error!"); //
}
//关闭session
session.Close(); 
return out;
}