通过WinInet API来实现表单提交并设置获取COOKIE

     可以尝试通过 HttpAddRequestHeaders 来添加自已的COOKIE:
char * lpszHeaders = "Cookie: Key=somevalue";
DWORD dwHeadersLength = strlen(lpszHeaders);
HttpAddRequestHeaders(hOpenRequest, lpszHeaders, dwHeadersLength,           HTTP_ADDREQ_FLAG_ADD);

     函数会返回成功,但实际上COOKIE可能并没有添加上去,建议在调用HttpOpenRequest时指定INTERNET_FLAG_NO_COOKIES选项。然而这个选项将阻止WinInet内部添加所需的COOKIE,因此你要负责所有必需的COOKIE。另一个函数InternetSetCookie也可以设置COOKIE,但我从未用过。

    如果需要检查返回的COOKIE,可以尝试使用HttpQueryInfo,并将其中的dwInfoLevel设置为HTTP_QUERY_SET_COOKIE。

     下面是MFC代码例子:

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: image/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 ;

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

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

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

你可能感兴趣的:(网络通讯&socket)