用WinHttp简单的Post数据

 1 BOOL KFunction::HttpPostData( LPCTSTR strUrl,LPCTSTR strData )
 2 {
 3     OutputDebugString(_T("URL:"));
 4     OutputDebugString(strUrl);
 5     OutputDebugString(_T("DATA:"));
 6     OutputDebugString(strData);
 7     bool bRtn = true;
 8     HINTERNET hSession = NULL;
 9     HINTERNET hConn = NULL;
10     HINTERNET hRequest = NULL;
11     do{
12         hSession = ::WinHttpOpen(_T("uninstall.exe"),WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,WINHTTP_NO_PROXY_NAME,WINHTTP_NO_PROXY_BYPASS,0);
13         if(NULL == hSession){
14             bRtn = false;
15             break;
16         }    
17 
18         URL_COMPONENTS urlComp = {sizeof(URL_COMPONENTS)};
19         TCHAR szHostName[MAX_PATH] = L"";
20         TCHAR szURLPath[MAX_PATH * 5] = L"";
21         urlComp.lpszHostName = szHostName;
22         urlComp.dwHostNameLength = MAX_PATH;
23         urlComp.lpszUrlPath = szURLPath;
24         urlComp.dwUrlPathLength = MAX_PATH * 5;
25         urlComp.dwSchemeLength = 1; // None zero
26         if(FALSE == ::WinHttpCrackUrl(strUrl,_tcslen(strUrl),0,&urlComp)){
27             bRtn = false;
28             break;
29         }
30         hConn = ::WinHttpConnect(hSession,urlComp.lpszHostName,80,NULL);
31         if(NULL == hConn){
32             bRtn = false;
33             break;
34         }
35         hRequest = ::WinHttpOpenRequest(hConn,_T("POST"),urlComp.lpszUrlPath,NULL,WINHTTP_NO_REFERER,WINHTTP_DEFAULT_ACCEPT_TYPES,0);
36 
37         CString headers;
38         headers.Format(_T("Content-Length:%d\r\nContent-Type: application/x-www-form-urlencoded\r\n"),_tcslen(strData));
39 
40         if(FALSE == ::WinHttpSendRequest(hRequest,headers,headers.GetLength(),WINHTTP_NO_REQUEST_DATA,0,0,NULL)){
41             bRtn = false;
42             break;
43         }
44         DWORD writeNum = 0;
45 #ifdef _UNICODE
46         char* szPostData = new char[_tcslen(strData)*2+1];
47         wcstombs(szPostData,strData,MAX_PATH);
48         if(FALSE == ::WinHttpWriteData(hRequest,(LPVOID)szPostData,strlen(szPostData),&writeNum)){
49 #else
50         if(FALSE == ::WinHttpWriteData(hRequest,(LPVOID)strData,strlen(strData),&writeNum)){
51 #endif
52             bRtn = false;
53             break;
54         }
55         OutputDebugString(_T("POST请求发送成功"));
56     }while(0);
57 
58     if(NULL != hRequest){
59         WinHttpCloseHandle(hSession);
60     }
61     if(NULL != hConn){
62         WinHttpCloseHandle(hSession);
63     }
64     if(NULL != hSession){
65         WinHttpCloseHandle(hSession);
66     }
67     return bRtn;
68 }

具体参考MSDN:http://msdn.microsoft.com/en-us/library/windows/desktop/aa384098(v=vs.85).aspx

posted @ 2013-10-23 20:46  ssp1024  阅读(3282)  评论(0编辑  收藏  举报