WinInet API實現表單提交併設置獲取COOKIE、http請求

能夠嘗試經過 HttpAddRequestHeaders 來添加自已的COOKIE:web


char * lpszHeaders = "Cookie: Key=somevalue";
DWORD dwHeadersLength = strlen(lpszHeaders);
HttpAddRequestHeaders(hOpenRequest, lpszHeaders, dwHeadersLength,          HTTP_ADDREQ_FLAG_ADD);
dom

 

     函數會返回成功,但實際上COOKIE可能並無添加上去,建議在調用HttpOpenRequest時指定 INTERNET_FLAG_NO_COOKIES選項。然而這個選項將阻止WinInet內部添加所需的COOKIE,所以你要負責全部必需的 COOKIE。另外一個函數InternetSetCookie也能夠設置COOKIE,但我從未用過。ide

 

    若是須要檢查返回的COOKIE,能夠嘗試使用HttpQueryInfo,並將其中的dwInfoLevel設置爲HTTP_QUERY_SET_COOKIE。函數

 

下面是MFC代碼例子:spa

 

try
{
     CInternetSession Session ;
     CHttpConnection *pHttpConnect = Session.GetHttpConnection( "www.abc.net" ) ;
     if( pHttpConnect )
     {
        CHttpFile* pFile = pHttpConnect->OpenRequest( CHttpConnection::HTTP_VERB_GET,
                 _T("/memberexists.srf?x="),
                 NULL,
                 1,
                 NULL,
                 NULL,
                 INTERNET_FLAG_NO_COOKIES ); //
    if ( pFile )
      
     pFile->AddRequestHeaders("Accept: p_w_picpath/png,*/*;q=0.5");
     pFile->AddRequestHeaders("Accept-Language: zh-cn,zh;q=0.5");
     pFile->AddRequestHeaders("Accept-Encoding: gzip,deflate");
     pFile->AddRequestHeaders("Accept-Charset: gb2312,utf-8;q=0.7,*;q=0.7");
     pFile->AddRequestHeaders("Keep-Alive: 300");
     pFile->AddRequestHeaders("Connection: keep-alive");
     pFile->AddRequestHeaders("Cookie: Key=somevalue;domain=abc.com") ;
    
     pFile->SendRequest();
    
     // 返回的HTML
     //CString s ;
     //while (pFile->ReadString(s))
     //str = s ;
.net

     // 取返回的COOKIE
     CString strInfo ;
     DWORD dw = 0 ;
     pFile->QueryInfo(HTTP_QUERY_SET_COOKIE ,strInfo ,&dw) ;
orm

     if (strInfo.IsEmpty()==FALSE)
        AfxMessageBox(strInfo) ;
    
ip

     pFile->Close();
     delete pFile ;
    }
   
   
    pHttpConnect->Close() ;
    delete pHttpConnect ;
   }
}
catch( CInternetException *e )
{
   e->Delete();    
}
utf-8

相關文章
相關標籤/搜索