用wininet实现http basic认证

今日需要做个在线升级的小工具,服务器为svn服务器,需要输密码,差了下http相关资料整理如下,以备后面需要:

 

    HINTERNET hOpenHandle,, hConnectHandle  hResourceHandle;  //分别为初始化,连
接及资源句柄
    DWORD dwStatus;
    DWORD dwStatusSize = sizeof(dwStatus);
    char strUsername[64] = "zjh", strPassword[64]="xxx";  //用户名及密码,可以通
过其他如交互方式等获取
   
    hOpenHandle = InternetOpen(TEXT("ZAgent"),
        INTERNET_OPEN_TYPE_PRECONFIG,
        NULL, NULL, 0);


    hConnectHandle = InternetConnect(hOpenHandle,
        TEXT("10.xx.xx.xx"),
        INTERNET_INVALID_PORT_NUMBER,
        NULL,
        NULL,
        INTERNET_SERVICE_HTTP,
        0,0);
   
    hResourceHandle = HttpOpenRequest(hConnectHandle, TEXT("GET"),
        TEXT("/svn/......."),         //路径
        NULL, NULL, NULL,
        INTERNET_FLAG_KEEP_CONNECTION,
        0);

   
    DWORD cchUserLength = strlen(strUsername), cchPasswordLength = strlen(
strPassword);

   BOOL    bConnectOK = FALSE;
    while (1)
    {
        HttpSendRequest(hResourceHandle, NULL, 0, NULL, 0);//发送请求
       
    HttpQueryInfo(hResourceHandle, HTTP_QUERY_FLAG_NUMBER |         //处理服务
器的返回信息,得到状态错误码
        HTTP_QUERY_STATUS_CODE, &dwStatus, &dwStatusSize, NULL);
       
        if (HTTP_STATUS_PROXY_AUTH_REQ == dwStatus)
        {
            InternetSetOption(hResourceHandle, INTERNET_OPTION_PROXY_USERNAME,
                strUsername,
                cchUserLength+1);
           
            InternetSetOption(hResourceHandle, INTERNET_OPTION_PROXY_PASSWORD,
                strPassword,
                cchPasswordLength+1);
            continue;
        }
        else if(HTTP_STATUS_DENIED == dwStatus)                //设置用户名密码
,这个也可以在前面直接设置,如果充分信任没被钓鱼的话
        {
            InternetSetOption(hResourceHandle, INTERNET_OPTION_USERNAME,
                strUsername, cchUserLength+1);
            InternetSetOption(hResourceHandle, INTERNET_OPTION_PASSWORD,
                strPassword, cchPasswordLength+1);        //这里如果密码一致错
误就死循环了,可以sleep一会并且可设定次数,达到失败次数也break且没有设置bConnect
OK.
            continue;
        }

 

bConnectOK  = TRUE;  //如果密码正确或不需要认证就到这里了
 break;


    }

 

   if(bConnectOK )

{

// InternetReadFile 读数据

}

 

你可能感兴趣的:(用wininet实现http basic认证)