Exemplo n.º 1
0
unsigned __stdcall 
CHttp::worker_HttpEndRequest(LPVOID  lp )
{
	HTTPENDREQUEST		*param = (HTTPENDREQUEST*)lp;

	return HttpEndRequest (param->hRequest, param->lpBuffersOut, param->dwFlags, param->dwContext );
}
Exemplo n.º 2
0
    void openHTTPConnection (URL_COMPONENTS& uc, URL::OpenStreamProgressCallback* progressCallback,
                             void* progressCallbackContext)
    {
        const TCHAR* mimeTypes[] = { _T("*/*"), 0 };

        DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_COOKIES;

        if (address.startsWithIgnoreCase ("https:"))
            flags |= INTERNET_FLAG_SECURE;  // (this flag only seems necessary if the OS is running IE6 -
                                            //  IE7 seems to automatically work out when it's https)

        request = HttpOpenRequest (connection, isPost ? _T("POST") : _T("GET"),
                                   uc.lpszUrlPath, 0, 0, mimeTypes, flags, 0);

        if (request != 0)
        {
            INTERNET_BUFFERS buffers = { 0 };
            buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
            buffers.lpcszHeader = headers.toWideCharPointer();
            buffers.dwHeadersLength = (DWORD) headers.length();
            buffers.dwBufferTotal = (DWORD) postData.getSize();

            if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
            {
                int bytesSent = 0;

                for (;;)
                {
                    const int bytesToDo = jmin (1024, (int) postData.getSize() - bytesSent);
                    DWORD bytesDone = 0;

                    if (bytesToDo > 0
                         && ! InternetWriteFile (request,
                                                 static_cast <const char*> (postData.getData()) + bytesSent,
                                                 (DWORD) bytesToDo, &bytesDone))
                    {
                        break;
                    }

                    if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
                    {
                        if (HttpEndRequest (request, 0, 0, 0))
                            return;

                        break;
                    }

                    bytesSent += bytesDone;

                    if (progressCallback != nullptr
                          && ! progressCallback (progressCallbackContext, bytesSent, (int) postData.getSize()))
                        break;
                }
            }
        }

        close();
    }
fsInternetResult fsHttpFile::Write(LPBYTE pBuffer, DWORD dwSize, DWORD *pdwWritten)
{
	if (m_hFile == NULL)
	{
		if (pdwWritten)
			*pdwWritten = 0;
		return IR_NOTINITIALIZED;
	}		

	if (m_uLeftToUpload == 0)
		return IR_S_FALSE;

	DWORD dwWritten;

	BOOL bRet = InternetWriteFile (m_hFile, pBuffer, dwSize, &dwWritten);

	if (pdwWritten)
		*pdwWritten = dwWritten;

	if (!bRet)
		return fsWinInetErrorToIR ();

	m_uLeftToUpload -= dwWritten;

	if (m_uLeftToUpload == 0)
	{
		if (m_bUseMultipart)
		{
			fsString str = "\r\n"; str += m_strLabel; str += "--\r\n";
			DWORD dw;
			if (FALSE == InternetWriteFile (m_hFile, str, str.GetLength (), &dw))
				return fsWinInetErrorToIR ();
		}

		bRet = HttpEndRequest (m_hFile, NULL, 0, NULL);
		if (!bRet)
			return fsWinInetErrorToIR ();
	}

	return IR_SUCCESS;
}
Exemplo n.º 4
0
BOOL CPostData::UseHttpSendReqEx( std::string& lpost)
{
	long lgg;
	lgg = lpost.size();

	USES_CONVERSION;
	INTERNET_BUFFERS BufferIn;
	DWORD dwBytesWritten;

	BOOL bRet;

	TCHAR head[1024];        
	std::wstring strt = MS_CONTENTTYPE;
	std::wstring strt1 = CA2W(CSNManager::GetInstance()->GetSN().c_str());
	_stprintf_s(head, _countof(head), _T("%s\r\nSN: %s;\r\nMoneyhubUID: %s;\r\n"), strt.c_str() ,strt1.c_str() ,m_strHWID.c_str());
	//TCHAR head[]= strt.c_str(); 

	BufferIn.dwStructSize = sizeof( INTERNET_BUFFERS ); // Must be set or error will occur
    BufferIn.Next = NULL; 
    BufferIn.lpcszHeader = head;
    BufferIn.dwHeadersLength = 0;
    BufferIn.dwHeadersTotal = sizeof(head);
    BufferIn.lpvBuffer = (LPSTR)lpost.c_str();                
    BufferIn.dwBufferLength = 0;
    BufferIn.dwBufferTotal = lgg; // This is the only member used other than dwStructSize
    BufferIn.dwOffsetLow = 0;
    BufferIn.dwOffsetHigh = 0;

    if(!HttpSendRequestEx( m_hInetFile, &BufferIn, NULL, 0, 2))
    {
		CloseHandles();
        printf( "Error on HttpSendRequestEx %d\n",GetLastError() );
        return FALSE;
    }

	bRet=TRUE;
	bRet = InternetWriteFile( m_hInetFile, (LPSTR)lpost.c_str(), lgg, &dwBytesWritten);

	if(!bRet)
	{
     	CloseHandles();
        printf( "\nError on InternetWriteFile %lu\n",GetLastError() );
        return FALSE;
    }

	bRet = HttpEndRequest(m_hInetFile, NULL, 0, 0);
    if(!bRet)
    {
    	CloseHandles();
        printf( "Error on HttpEndRequest %lu \n", GetLastError());
        return FALSE;
    }

		char pcBuffer[BUFFSIZE];
		DWORD dwBytesRead;
	    LPSTR	lpszData1;
		lpszData1 = new char[1024*1024];
		lpszData1[0]='\0';

		//printf("\nThe following was returned by the server:\n");
		do
		{	dwBytesRead=0;
			if(InternetReadFile(m_hInetFile, pcBuffer, BUFFSIZE-1, &dwBytesRead))
			{
				pcBuffer[dwBytesRead]=0x00; // Null-terminate buffer
        		strcat(lpszData1,pcBuffer);
				//printf("%s", pcBuffer);
			}
			else
                return FALSE;
				//lpszData1 ="";
				//printf("\nInternetReadFile failed");
		}while(dwBytesRead>0);
		//printf("\n");
		lpost = "";
		lpost = CW2A(UTF8ToUnicode(lpszData1).c_str());
	    delete []lpszData1;

	CloseHandles();
	//return  ERR_SUCCESS;
	return TRUE;
}
Exemplo n.º 5
0
CNetDataImpl* CNetRequestImpl::sendStream(common::InputStream* bodyStream)
{
    CNetDataImpl* pNetData = new CNetDataImpl;

    do
    {
        if ( isError() )
            break;

        if ( !HttpAddRequestHeaders( hRequest, szMultipartContType, -1, HTTP_ADDREQ_FLAG_ADD|HTTP_ADDREQ_FLAG_REPLACE ) )
        {
            pszErrFunction = L"HttpAddRequestHeaders";
            break;
        }

	    INTERNET_BUFFERS BufferIn;
        memset(&BufferIn, 0, sizeof(INTERNET_BUFFERS));
	    BufferIn.dwStructSize = sizeof( INTERNET_BUFFERS ); // Must be set or error will occur
        BufferIn.dwBufferTotal = bodyStream->available() + strlen(szMultipartPrefix) + strlen(szMultipartPostfix);

        if(!HttpSendRequestEx( hRequest, &BufferIn, NULL, 0, 0))
        {
            pszErrFunction = L"HttpSendRequestEx";
            break;
        }

	    DWORD dwBytesWritten = 0;
        if ( !InternetWriteFile( hRequest, szMultipartPrefix, strlen(szMultipartPrefix), &dwBytesWritten) )
        {
            pszErrFunction = L"InternetWriteFile";
            break;
        }

        DWORD dwBufSize = 4096;
        char* pBuf = (char*)malloc(dwBufSize);
        int nReaded = 0;

	    do
	    {
            nReaded = bodyStream->read(pBuf,0,dwBufSize);
            if ( nReaded > 0 )
            {
		        if ( !InternetWriteFile( hRequest, pBuf, nReaded, &dwBytesWritten) )
                {
                    pszErrFunction = L"InternetWriteFile";
                    break;
                }
            }
	    }while(nReaded > 0);

        free(pBuf);

        if ( !InternetWriteFile( hRequest, szMultipartPostfix, strlen(szMultipartPostfix), &dwBytesWritten) )
        {
            pszErrFunction = L"InternetWriteFile";
            break;
        }

        if ( !HttpEndRequest(hRequest, NULL, 0, 0) )
        {
            pszErrFunction = L"HttpEndRequest";
            break;
        }

        if ( isError() )
            break;

        readResponse(pNetData);
    }while(0);

    return pNetData;
}
Exemplo n.º 6
0
bool HttpPost(const WCHAR *server, const WCHAR *url, str::Str<char> *headers, str::Str<char> *data)
{
    str::Str<char> resp(2048);
    bool ok = false;
    HINTERNET hConn = NULL, hReq = NULL;
    HINTERNET hInet = InternetOpen(USER_AGENT, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
    if (!hInet)
        goto Exit;
    hConn = InternetConnect(hInet, server, INTERNET_DEFAULT_HTTP_PORT,
                            NULL, NULL, INTERNET_SERVICE_HTTP, 0, 1);
    if (!hConn)
        goto Exit;

    DWORD flags = INTERNET_FLAG_KEEP_CONNECTION;
    hReq = HttpOpenRequest(hConn, L"POST", url, NULL, NULL, NULL, flags, NULL);
    if (!hReq)
        goto Exit;
    char *hdr = NULL;
    DWORD hdrLen = 0;
    if (headers && headers->Count() > 0) {
        hdr = headers->Get();
        hdrLen = (DWORD)headers->Count();
    }
    void *d = NULL;
    DWORD dLen = 0;
    if (data && data->Count() > 0) {
        d = data->Get();
        dLen = (DWORD)data->Count();
    }

    unsigned int timeoutMs = 15 * 1000;
    InternetSetOption(hReq, INTERNET_OPTION_SEND_TIMEOUT,
                      &timeoutMs, sizeof(timeoutMs));

    InternetSetOption(hReq, INTERNET_OPTION_RECEIVE_TIMEOUT,
                      &timeoutMs, sizeof(timeoutMs));

    if (!HttpSendRequestA(hReq, hdr, hdrLen, d, dLen))
        goto Exit;

    // Get the response status.
    DWORD respHttpCode = 0;
    DWORD respHttpCodeSize = sizeof(respHttpCode);
    HttpQueryInfo(hReq, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER,
                       &respHttpCode, &respHttpCodeSize, 0);

    DWORD dwRead;
    do {
        char buf[1024];
        if (!InternetReadFile(hReq, buf, sizeof(buf), &dwRead))
            goto Exit;
        resp.Append(buf, dwRead);
    } while (dwRead > 0);

#if 0
    // it looks like I should be calling HttpEndRequest(), but it always claims
    // a timeout even though the data has been sent, received and we get HTTP 200
    if (!HttpEndRequest(hReq, NULL, 0, 0)) {
        LogLastError();
        goto Exit;
    }
#endif
    ok = (200 == respHttpCode);
Exit:
    if (hReq)
        InternetCloseHandle(hReq);
    if (hConn)
        InternetCloseHandle(hConn);
    if (hInet)
        InternetCloseHandle(hInet);
    return ok;
}
Exemplo n.º 7
0
bool Download::httpSendReqEx(HINTERNET hConnect, const string &dest,
                             const vector< pair<string, string> > &headers,
                             const string &upFile, const string &outFile, ProgressWindow &pw) const {
  INTERNET_BUFFERS BufferIn;
  memset(&BufferIn, 0, sizeof(BufferIn));
  BufferIn.dwStructSize = sizeof( INTERNET_BUFFERS );

  HINTERNET hRequest = HttpOpenRequest (hConnect, "POST", dest.c_str(), NULL, NULL, NULL, INTERNET_FLAG_NO_CACHE_WRITE, 0);

  DWORD dwBytesRead = 0;
  DWORD dwBytesWritten = 0;
  BYTE pBuffer[4*1024]; // Read from file in 4K chunks

  string hdr;
  for (size_t k = 0; k<headers.size(); k++) {
    if (!trim(headers[k].second).empty()) {
      hdr += headers[k].first + ": " + headers[k].second + "\r\n";
    }
  }

  int retry = 5;
  while (retry>0) {

    HANDLE hFile = CreateFile(upFile.c_str(), GENERIC_READ, FILE_SHARE_READ,
                              NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

    if (hFile == HANDLE(-1))
      return false;


    BufferIn.dwBufferTotal = GetFileSize (hFile, NULL);
    BufferIn.dwHeadersLength = hdr.length();
    BufferIn.lpcszHeader = hdr.c_str();

    double totSize = BufferIn.dwBufferTotal;

    if (!HttpSendRequestEx( hRequest, &BufferIn, NULL, 0, 0)) {
      CloseHandle(hFile);
      InternetCloseHandle(hRequest);
      return false;
    }

    DWORD sum = 0;
    do {
      if (!ReadFile (hFile, pBuffer, sizeof(pBuffer), &dwBytesRead, NULL)) {
        CloseHandle(hFile);
        InternetCloseHandle(hRequest);
        return false;
      }

      if (dwBytesRead > 0) {
        if (!InternetWriteFile(hRequest, pBuffer, dwBytesRead, &dwBytesWritten)) {
          CloseHandle(hFile);
          InternetCloseHandle(hRequest);
          return false;
        }
      }
      sum += dwBytesWritten;

      try {
        pw.setProgress(int(1000 * double(sum) / totSize));
      }
      catch (std::exception &) {
        CloseHandle(hFile);
        InternetCloseHandle(hRequest);
        throw;
      }
    }
    while (dwBytesRead == sizeof(pBuffer)) ;

    CloseHandle(hFile);

    if (!HttpEndRequest(hRequest, NULL, 0, 0)) {
      DWORD error = GetLastError();
      if (error == ERROR_INTERNET_FORCE_RETRY)
        retry--;
      else if (error == ERROR_INTERNET_TIMEOUT) {
        throw std::exception("Fick inget svar i tid (ERROR_INTERNET_TIMEOUT)");
      }
      else {
        InternetCloseHandle(hRequest);
        return false;
      }
    }
    else
      retry = 0; // Done
  }

  DWORD dwStatus = 0;
  DWORD dwBufLen = sizeof(dwStatus);
  int success = HttpQueryInfo(hRequest, HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER,
                                        (LPVOID)&dwStatus, &dwBufLen, 0);

  if (success) {
    if (dwStatus >= 400) {
      char bf[256];
      switch (dwStatus) {
        case HTTP_STATUS_BAD_REQUEST:
          sprintf_s(bf, "HTTP Error 400: The request could not be processed by the server due to invalid syntax.");
          break;
        case HTTP_STATUS_DENIED:
          sprintf_s(bf, "HTTP Error 401: The requested resource requires user authentication.");
          break;
        case HTTP_STATUS_FORBIDDEN:
          sprintf_s(bf, "HTTP Error 403: Åtkomst nekad (access is denied).");
          break;
        case HTTP_STATUS_NOT_FOUND:
          sprintf_s(bf, "HTTP Error 404: Resursen kunde ej hittas (not found).");
          break;
        case HTTP_STATUS_NOT_SUPPORTED:
          sprintf_s(bf, "HTTP Error 501: Förfrågan stöds ej (not supported).");
          break;
        case HTTP_STATUS_SERVER_ERROR:
          sprintf_s(bf, "HTTP Error 500: Internt serverfel (server error).");
          break;
        default:
          sprintf_s(bf, "HTTP Status Error %d", dwStatus);
      }
      throw dwException(bf, dwStatus);
    }
  }

  int fileno = _open(outFile.c_str(), O_BINARY|O_CREAT|O_WRONLY|O_TRUNC, S_IREAD|S_IWRITE);

  do {
    dwBytesRead=0;
    if (InternetReadFile(hRequest, pBuffer, sizeof(pBuffer)-1, &dwBytesRead)) {
      _write(fileno, pBuffer, dwBytesRead);
    }
  } while(dwBytesRead>0);

  _close(fileno);

  InternetCloseHandle(hRequest);
  return true;
}
Exemplo n.º 8
0
STDMETHODIMP HttpRequest::Send(IHttpResponse** pVal)
{
    
	HRESULT hr=S_OK;
    
	ATLASSERT(pVal);
	(*pVal)=NULL;
	if(!this->m_szUrl || _tcslen(this->m_szUrl)==0) {
		InfoMsgBox(_T("请先指定请求的目标URL地址!"));
		return hr;
	}
    
	//显示进度
	rcContext.hOpen=this->m_hOpen;
	rcContext.dwPostFileLength=0;
	rcContext.dwPostedLength=0;
	rcContext.dwContentLength=0;
	rcContext.dwReceivedLength=0;
	if (this->m_blShowRequestProgress){
		ZeroMemory(rcContext.szMemo,sizeof(rcContext.szMemo));//STRLEN_DEFAULT);
		_tcscpy_s(rcContext.szMemo,_T("请稍候,正在准备连接..."));
		rcContext.hThread=CreateThread(NULL, 0,(LPTHREAD_START_ROUTINE)ProgressDialog,0,0,&(rcContext.dwThreadID));
	}

	//请求方法
	TCHAR szUrl[STRLEN_4K]={0};
	_tcscpy_s(szUrl,m_szUrl);
	TCHAR szMethod[STRLEN_SMALL]=_T("POST");
	if(this->m_szMethod && _tcslen(this->m_szMethod)>0){
		ZeroMemory(szMethod,sizeof(szMethod));
		_tcscpy_s(szMethod,m_szMethod);
	}

	//±äÁ¿¶¨Òå
	DWORD dwError=0;
	DWORD dwFlags=0;
	HINTERNET hConnect=0;			//Internetȇȡ
	HINTERNET hRequest=0;			//InternetÁ¬½Ó
	INTERNET_PORT dwPort;

	BOOL postFileFlag=FALSE;	//ÊÇ·ñÓÐÓÐЧµÄÌá½»Îļþ¡£
	HANDLE hPostFile=0;
	DWORD dwPostFileSize=0;

	BOOL sendRequestSucceeded=TRUE;	//·¢ËÍÇëÇóÊÇ·ñ³É¹¦

	DWORD dwSize=0;

	DWORD dwStatusCode=0;	//httpÇëÇóÏìÓ¦´úÂë
	DWORD dwContentLength=0;	//httpÇëÇóÏìÓ¦ÄÚÈݳ¤¶È
	DWORD dwErrorCode=0;	//httpÇëÇóÏìÓ¦´íÎóÂë
	TCHAR szContentType[STRLEN_DEFAULT]={0};	//httpÇëÇóÏìÓ¦ÄÚÈÝÀàÐÍ
	CComBSTR szResText(L"");				//httpÇëÇóÏìÓ¦·µ»Ø½á¹ûÎı¾
	TCHAR* szHeader=NULL;	//httpÇëÇóÏìӦͷÐÅÏ¢

	BOOL getHeanderSucceeded=TRUE;	//»ñÈ¡httpÇëÇóÏìӦͷÐÅÏ¢ÊÇ·ñ³É¹¦

	char readBuffer[STRLEN_1K]={0};	//ÿ´Î¶ÁÈ¡µÄÏìÓ¦ÄÚÈÝ
	DWORD dwCalcLength=0;	//ͨ¹ýÄÚÈݼÆËã³öÀ´µÄContentLength
	
	BOOL responseFileFlag=FALSE;	//ÊÇ·ñÓÐÓÐЧµÄÏìÓ¦ÄÚÈݱ¾µØ±£´æÎļþ
	HANDLE hResponseFile=0;	//ÇëÇóÏìÓ¦ÄÚÈݱ£´æµ½±¾µØÎļþµÄÎļþ¾ä±ú

	int requestCount=1;	//ÇëÇó´ÎÊý
	
	TCHAR szAccept[] = _T("*/*");
	LPTSTR AcceptTypes[2]={0};
	AcceptTypes[0]=szAccept;
	AcceptTypes[1]=NULL;

	
	CComPtr<IHttpResponse> response;	//ÇëÇóÏìÓ¦¶ÔÏó

	//Á¬½Ó
	dwPort=this->m_usUrlPort;	//¶Ë¿ÚºÅ
	dwFlags= INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_RELOAD |INTERNET_FLAG_KEEP_CONNECTION;
	if (this->m_blUrlIsSSL) dwFlags |= INTERNET_FLAG_SECURE | INTERNET_FLAG_IGNORE_CERT_CN_INVALID | INTERNET_FLAG_IGNORE_CERT_DATE_INVALID;
	
	//´ò¿ªÁ¬½Ó
	if ( !(hConnect = InternetConnect(this->m_hOpen,this->m_szUrlHost , dwPort, _T(""),  _T(""), INTERNET_SERVICE_HTTP, 0, (DWORD)&rcContext))){
		dwError=GetLastError();
		ErrorMsgBox(dwError,_T("Internet连接错误:%s"));
		goto clean;
	}
	
reconnect:
	//´ò¿ªÇëÇó
	if ( !(hRequest = HttpOpenRequest(hConnect,this->m_szMethod,this->m_szUrlFile, _T("HTTP/1.1"), _T(""),(LPCTSTR*)AcceptTypes, dwFlags ,(DWORD)&rcContext))){
		dwError=GetLastError();
		ErrorMsgBox(dwError,_T("Internet打开请求错误:%s"));
		goto clean;
	}
	
	//ÓÐÖ¸¶¨Ìá½»Îļþ
	if (this->m_szPostFile && _tcslen(this->m_szPostFile)) {
		postFileFlag=PathFileExists(this->m_szPostFile);
	}
	
	//Èç¹ûÓÐÌá½»µÄÎļþ
	if(postFileFlag) {
		if ((hPostFile = CreateFile(this->m_szPostFile,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,(HANDLE)NULL)) == (HANDLE)(-1))
		{
			dwError=GetLastError();
			ErrorMsgBox(dwError,_T("提交的文件不存在或者无法打开:%s"));			
			goto clean;
		}        
		dwPostFileSize=GetFileSize(hPostFile,NULL);
		rcContext.dwPostFileLength=dwPostFileSize;
		TCHAR szPostFileSize[STRLEN_SMALL]={0};
		_stprintf_s(szPostFileSize,_T("%d"),dwPostFileSize);
		this->AddHeader(T2BSTR(_T("Content-Length")),T2BSTR(szPostFileSize));
	}
	
	//ÉèÖÃÇëÇóÍ·
	if (this->m_szHeader && _tcslen(this->m_szHeader)) {
		if (!HttpAddRequestHeaders(hRequest,this->m_szHeader,-1L,HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD)){
			dwError=GetLastError();
			ErrorMsgBox(dwError,_T("设置请求头错误:%s"));
			goto clean;
		}
	}
	/*
	InternetSetOption(FhRequest,     
                  INTERNET_OPTION_CLIENT_CERT_CONTEXT,   
                  (LPVOID)pdDesiredCert,     
                  sizeof(CERT_CONTEXT));   
 INTERNET_FLAG_KEEP_CONNECTION£¬INTERNET_FLAG_EXISTING_CONNECT
	*/
	//´¦Àí¶îÍâÉèÖ㨺öÂÔһЩ´íÎó£©
	dwFlags=0;
	dwFlags |= SECURITY_FLAG_IGNORE_UNKNOWN_CA|SECURITY_FLAG_IGNORE_REVOCATION|SECURITY_FLAG_IGNORE_REDIRECT_TO_HTTP|SECURITY_FLAG_IGNORE_REDIRECT_TO_HTTPS|SECURITY_FLAG_IGNORE_CERT_DATE_INVALID|SECURITY_FLAG_IGNORE_CERT_CN_INVALID;
	if (!InternetSetOption (hRequest, INTERNET_OPTION_SECURITY_FLAGS,&dwFlags,sizeof(dwFlags))){
		dwError=GetLastError();
		ErrorMsgBox(dwError,_T("设置请求选项错误:%s"));
		goto clean;
	}
	
	//·¢ËÍÇëÇó
again:
	if(postFileFlag){	//ÓÐÌá½»ÎļþÄÚÈÝ
		INTERNET_BUFFERS BufferIn = {0};
		DWORD dwBytesWritten;
		BYTE bts[STRLEN_1K]={0};
		DWORD dwBtsRead=0;
		DWORD dwTotalBytes=0;

		BufferIn.dwStructSize = sizeof(INTERNET_BUFFERS);
		BufferIn.Next=NULL;
		BufferIn.dwBufferTotal=dwPostFileSize;

		sendRequestSucceeded=HttpSendRequestEx(hRequest, &BufferIn, NULL, HSR_INITIATE,(DWORD)&rcContext);
		
		while(ReadFile(hPostFile, bts, STRLEN_1K, &dwBtsRead, NULL) && dwBtsRead>0 && dwTotalBytes<=dwPostFileSize){
			if (!InternetWriteFile(hRequest, bts,dwBtsRead, &dwBytesWritten))
			{
				dwError=GetLastError();
				ErrorMsgBox(dwError,_T("发送文件内容错误:%s"));
				goto clean;
			}
			dwTotalBytes+=dwBtsRead;
			rcContext.dwPostedLength=dwTotalBytes;
		}
		
		if(!HttpEndRequest(hRequest, NULL, 0, 0))
		{
			dwError=GetLastError();
			ErrorMsgBox(dwError,_T("关闭HTTP连接时错误:%s"));
			goto clean;
		}
	}//if end
	else{	//ûÓÐÌá½»ÎļþÄÚÈÝ
		sendRequestSucceeded=HttpSendRequest(hRequest, NULL, 0, NULL, 0);
	}	//else end

	//²é¿´ÊÇ·ñÇëÇó·¢Ëͳɹ¦
	if (!sendRequestSucceeded){
		dwError=GetLastError();
		switch(dwError){
			case ERROR_INTERNET_CLIENT_AUTH_CERT_NEEDED:
				if(InternetErrorDlg(GetDesktopWindow(),hRequest,ERROR_INTERNET_CLIENT_AUTH_CERT_NEEDED,FLAGS_ERROR_UI_FILTER_FOR_ERRORS|FLAGS_ERROR_UI_FLAGS_GENERATE_DATA|FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS,NULL)!=ERROR_SUCCESS)
				{
					requestCount++;
					if (requestCount>2) {
						InfoMsgBox(_T("已经尝试发送请求操作2次仍无法成功,请联系系统管理员!"));
						goto clean;
					}	//Èç¹ûÑ­»·ÇëÇó´ÎÊý¶àÓÚÁ½´Î£¬ÄÇô²»ÔÙÑ­»·
					else goto again;
				}
				break;
			case ERROR_SUCCESS:
				break;
			default:
				ErrorMsgBox(dwError,_T("发送请求错误:%s"));
				goto clean;
		}//switch end
	}//if end

	//È¡ÏìӦ״̬ÏûÏ¢
	dwSize= sizeof(DWORD);
	if (!HttpQueryInfo(hRequest,HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &dwStatusCode, &dwSize, NULL))
	{
		dwError=GetLastError();
		ErrorMsgBox(dwError,_T("获取响应代码错误:%s"));
		goto clean;
	}

	switch(dwStatusCode){
		case HTTP_STATUS_DENIED:	//ÐèÒªµÇ¼
		case HTTP_STATUS_PROXY_AUTH_REQ:
			InfoMsgBox(_T("请求的地址需要登录,请您先登录后再发送请求!"));
			goto clean;
		case HTTP_STATUS_REDIRECT:	//Öض¨Ïò
		case HTTP_STATUS_MOVED:
			{
				TCHAR szRedirect[4096]={0};
				DWORD dwRedirect=sizeof(szRedirect);
				if (!HttpQueryInfo(hRequest,HTTP_QUERY_LOCATION,(LPVOID)szRedirect,&dwRedirect,NULL)){
					dwError=GetLastError();
					ErrorMsgBox(hr,_T("获取重定向地址错误:%s"));
					goto clean;
				}
				this->put_Url(szRedirect);
				//ÏȹرÕÁ¬½ÓºÍÇëÇó£¬È»ºóÖØÐÂÁ¬½Ó
				if (!InternetCloseHandle(hRequest))
				{
					dwError=GetLastError();
					ErrorMsgBox(dwError,_T("关闭HTTP请求错误:%s"));
					goto clean;
				}
				//if (!InternetCloseHandle(hConnect))
				//{
				//	dwError=GetLastError();
				//	ErrorMsgBox(dwError,_T("关闭HTTP连接错误:%s"));
				//	goto clean;
				//}
				//MessageBox(0,szRedirect,_T("重定向"),0);
				goto reconnect;
			}
		case HTTP_STATUS_OK:
		default:
			break;
	}

	//¹¹ÔìÇëÇóÏìÓ¦¡£
	response.p=NULL;
	hr=response.CoCreateInstance(_T("YRExchange.HttpResponse"));
	if (FAILED(hr)) {
		ErrorMsgBox(hr,_T("创建HttpResponse错误:%s"));
		goto clean;
	}
	response->put_StatusCode(dwStatusCode);
	response->put_ErrorCode(dwError);

	//ÏìÓ¦ÄÚÈÝ´óС
	dwSize=sizeof(dwContentLength);
	if (HttpQueryInfo(hRequest,HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER ,&dwContentLength,&dwSize,NULL)){
		//dwError=GetLastError();	
		//ErrorMsgBox(dwError,_T("获取请求响应内容长度错误:%s"));
		//goto clean;
		if (dwContentLength>0) {
			response->put_ContentLength(dwContentLength);
			rcContext.dwContentLength=dwContentLength;
		}
	}

	//ÏìÓ¦ÄÚÈÝÀàÐÍ 
	dwSize=sizeof(szContentType);
	if (HttpQueryInfo(hRequest,HTTP_QUERY_CONTENT_TYPE ,(LPVOID)szContentType,&dwSize,NULL)){
		//dwError=GetLastError();	
		//ErrorMsgBox(dwError,_T("获取请求响应内容类型错误:%s"));
		//goto clean;
		if (_tcslen(szContentType)>0) response->put_ContentType(T2BSTR(szContentType));
	}
	
	//ËùÓÐÏìӦͷÐÅÏ¢
	szHeader=new TCHAR[STRLEN_8K];
	dwSize=STRLEN_8K*sizeof(TCHAR);
getheader:
	getHeanderSucceeded=HttpQueryInfo(hRequest,HTTP_QUERY_RAW_HEADERS_CRLF ,(LPVOID)szHeader,&dwSize,NULL);
	if(!getHeanderSucceeded){
		dwError=GetLastError();
		if (dwError==ERROR_INSUFFICIENT_BUFFER){
			TCHAR szXX[100]={0};
			_stprintf_s(szXX,_T("dwError=%d,dwSize=%d"),dwError,dwSize);
			InfoMsgBox(szXX);
			SAFE_FREE_STRING_PTR(szHeader);
			szHeader=new TCHAR[dwSize+2];
			dwSize+=2;
			dwSize=dwSize*sizeof(TCHAR);
			goto getheader;
		}
		else if (dwError!=ERROR_SUCCESS){
			ErrorMsgBox(dwError,_T("获取请求响应头信息错误:%s"));
			goto clean;
		}
	}
	if(szHeader) response->put_Header(T2BSTR(szHeader));
	//ÏìÓ¦ÄÚÈÝ´¦Àí
	if (this->m_blSaveResponseToFile && this->m_szResponseFile && _tcslen(this->m_szResponseFile)>0 && dwStatusCode != 201){	//°ÑÏìÓ¦ÄÚÈݱ£´æµ½Îļþ
		//´´½¨Îļþ 
		hResponseFile = CreateFile(this->m_szResponseFile,GENERIC_WRITE,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
		if (hResponseFile == INVALID_HANDLE_VALUE) 
		{ 
			dwError=GetLastError();
			ErrorMsgBox(dwError,_T("打开响应内容本地保存文件错误:%s"));
			goto clean;
		}
		responseFileFlag=TRUE;
	}
	do{
		ZeroMemory(readBuffer,STRLEN_1K);
		dwSize=0;
		if (!InternetReadFile(hRequest,(LPVOID)readBuffer,sizeof(readBuffer),&dwSize)){
			dwError=GetLastError();
			ErrorMsgBox(dwError,_T("读取请求响应内容错误:%s"));
			goto clean;
		}
		if (dwSize!=0){
			dwCalcLength+=dwSize;
			if (responseFileFlag){	//дÎļþ
				DWORD dwWritten=0;
				if (!WriteFile(hResponseFile,readBuffer,dwSize,&dwWritten,NULL)){
					dwError=GetLastError();
					ErrorMsgBox(dwError,_T("写入响应内容本地保存文件错误:%s"));
					goto clean;
				}
			}
			else{	//×·¼Óµ½ÏàÓ¦Îı¾
				char buffer[STRLEN_1K+2]={0};
				strncpy_s(buffer,readBuffer,dwSize);
				if (szResText) szResText.Append(buffer);
			}
			if (dwCalcLength==dwContentLength) break;
			rcContext.dwReceivedLength=dwCalcLength;
		}//if end
	}while(dwSize!=0);
	
	//°ÑÏìÓ¦ÄÚÈݱ£´æµ½ÏìÓ¦Îı¾
	if (!responseFileFlag){
		response->put_ContentText(szResText.Detach());
	}//
	//×ÊÔ´»ØÊÕ
clean:
	//¹Ø±ÕÎļþ
	if(hPostFile) CloseHandle(hPostFile);
	if(hResponseFile) {
		FlushFileBuffers(hResponseFile);
		CloseHandle(hResponseFile);
	}

	//»ØÊÕhttpÁ¬½ÓºÍÇëÇó¾ä±ú
	if (hRequest) InternetCloseHandle(hRequest);
	if (hConnect) InternetCloseHandle(hConnect);

	//¹Ø±Õ״̬¿ò
	//if (this->m_blShowRequestProgress) WaitForMultipleObjects(1,&rcContext.hThread,TRUE,INFINITE); 
	if (this->m_blShowRequestProgress) EndDialog(rcContext.hProgressWnd,0);

	SAFE_FREE_STRING_PTR(szHeader);

	response.CopyTo(pVal);

	return S_OK;
}
Exemplo n.º 9
0
// Sends HTTP request and checks response
BOOL CHttpRequestSender::InternalSend()
{ 
    BOOL bStatus = FALSE;      // Resulting status
    strconv_t strconv;         // String conversion
    HINTERNET hSession = NULL; // Internet session
    HINTERNET hConnect = NULL; // Internet connection
    HINTERNET hRequest = NULL; // Handle to HTTP request
    TCHAR szProtocol[512];     // Protocol
    TCHAR szServer[512];       // Server name
    TCHAR szURI[1024];         // URI
    DWORD dwPort=0;            // Port
    CString sHeaders = _T("Content-type: multipart/form-data; boundary=") + m_sBoundary;
    LPCTSTR szAccept[2]={_T("*/*"), NULL};
    INTERNET_BUFFERS BufferIn;
    BYTE pBuffer[4096] = {0};
    BOOL bRet = FALSE;
    DWORD dwBuffSize = 0;
    CString sMsg;
    LONGLONG lPostSize = 0;  
    std::map<CString, std::string>::iterator it;
    std::map<CString, CHttpRequestFile>::iterator it2;

    // Calculate size of data to send
    m_Assync->SetProgress(_T("Calculating size of data to send."), 0);
    bRet = CalcRequestSize(lPostSize);
    if(!bRet)
    {
        m_Assync->SetProgress(_T("Error calculating size of data to send!"), 0);
        goto cleanup;
    }

    // Create Internet session
    m_Assync->SetProgress(_T("Opening Internet connection."), 0);
    hSession = InternetOpen(_T("CrashRpt"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
    if(hSession==NULL)
    {
        m_Assync->SetProgress(_T("Error opening Internet session"), 0);
        goto cleanup; 
    }

    // Parse application-provided URL
    ParseURL(m_Request.m_sUrl, szProtocol, 512, szServer, 512, dwPort, szURI, 1024);

    // Connect to HTTP server
    m_Assync->SetProgress(_T("Connecting to server"), 0, true);

    hConnect = InternetConnect(
        hSession,     // InternetOpen handle
        szServer,     // Server  name
        (WORD)dwPort, // Default HTTPS port - 443
        NULL,         // User name
        NULL,         //  User password
        INTERNET_SERVICE_HTTP, // Service
        0,            // Flags
        0             // Context
        );
    if(hConnect==NULL)
    {
        m_Assync->SetProgress(_T("Error connecting to server"), 0);
        goto cleanup; 
    }
	
	// Set large receive timeout to avoid problems in case of 
	// slow upload => slow response from the server.
	DWORD dwReceiveTimeout = 0;
	InternetSetOption(hConnect, INTERNET_OPTION_RECEIVE_TIMEOUT, 
		&dwReceiveTimeout, sizeof(dwReceiveTimeout));

    // Check if canceled
    if(m_Assync->IsCancelled()){ goto cleanup; }

    // Add a message to log
    m_Assync->SetProgress(_T("Opening HTTP request..."), 0, true);

    // Configure flags for HttpOpenRequest
    DWORD dwFlags = INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_AUTO_REDIRECT;
    if(dwPort==INTERNET_DEFAULT_HTTPS_PORT)
	    dwFlags |= INTERNET_FLAG_SECURE; // Use SSL
	
	BOOL bRedirect = FALSE;
	int nCount = 0;
	while(nCount==0 || bRedirect)
	{
		nCount++;

		// Open HTTP request
		hRequest = HttpOpenRequest(
			hConnect, 
			_T("POST"), 
			szURI, 
			NULL, 
			NULL, 
			szAccept, 
			dwFlags, 
			0
			);
		if (!hRequest)
		{
			m_Assync->SetProgress(_T("HttpOpenRequest has failed."), 0, true);
			goto cleanup;
		}

		// This code was copied from http://support.microsoft.com/kb/182888 to address the problem
		// that MVS doesn't have a valid SSL certificate.
		DWORD extraSSLDwFlags = 0;
		DWORD dwBuffLen = sizeof(extraSSLDwFlags);
		InternetQueryOption (hRequest, INTERNET_OPTION_SECURITY_FLAGS,
		(LPVOID)&extraSSLDwFlags, &dwBuffLen);
		// We have to specifically ignore these 2 errors for MVS	
		extraSSLDwFlags |= SECURITY_FLAG_IGNORE_REVOCATION |  // Ignores certificate revocation problems.
						   SECURITY_FLAG_IGNORE_WRONG_USAGE | // Ignores incorrect usage problems.
						   SECURITY_FLAG_IGNORE_CERT_CN_INVALID | // Ignores the ERROR_INTERNET_SEC_CERT_CN_INVALID error message.
						   SECURITY_FLAG_IGNORE_CERT_DATE_INVALID; // Ignores the ERROR_INTERNET_SEC_CERT_DATE_INVALID error message.
		InternetSetOption (hRequest, INTERNET_OPTION_SECURITY_FLAGS,
							&extraSSLDwFlags, sizeof (extraSSLDwFlags) );

		// Fill in buffer
		BufferIn.dwStructSize = sizeof( INTERNET_BUFFERS ); // Must be set or error will occur
		BufferIn.Next = NULL; 
		BufferIn.lpcszHeader = sHeaders;
		BufferIn.dwHeadersLength = sHeaders.GetLength();
		BufferIn.dwHeadersTotal = 0;
		BufferIn.lpvBuffer = NULL;                
		BufferIn.dwBufferLength = 0;
		BufferIn.dwBufferTotal = (DWORD)lPostSize; // This is the only member used other than dwStructSize
		BufferIn.dwOffsetLow = 0;
		BufferIn.dwOffsetHigh = 0;

		m_dwPostSize = (DWORD)lPostSize;
		m_dwUploaded = 0;

		// Add a message to log
		m_Assync->SetProgress(_T("Sending HTTP request..."), 0);
		// Send request
		if(!HttpSendRequestEx( hRequest, &BufferIn, NULL, 0, 0))
		{
			m_Assync->SetProgress(_T("HttpSendRequestEx has failed."), 0);
			goto cleanup;
		}

		// Write text fields
		for(it=m_Request.m_aTextFields.begin(); it!=m_Request.m_aTextFields.end(); it++)
		{
			bRet = WriteTextPart(hRequest, it->first); 
			if(!bRet)
				goto cleanup;
		}

		// Write attachments
		for(it2=m_Request.m_aIncludedFiles.begin(); it2!=m_Request.m_aIncludedFiles.end(); it2++)
		{
			bRet = WriteAttachmentPart(hRequest, it2->first); 
			if(!bRet)
				goto cleanup;
		}

		// Write boundary
		bRet = WriteTrailingBoundary(hRequest);
		if(!bRet)
			goto cleanup;

		// Add a message to log
		m_Assync->SetProgress(_T("Ending HTTP request..."), 0);

		// End request
		if(!HttpEndRequest(hRequest, NULL, 0, 0))
		{
			m_Assync->SetProgress(_T("HttpEndRequest has failed."), 0);
			goto cleanup;
		}

		// Add a message to log
		m_Assync->SetProgress(_T("Reading server response..."), 0);
	
		// Get HTTP response code from HTTP headers
		DWORD lHttpStatus = 0;
		DWORD lHttpStatusSize = sizeof(lHttpStatus);
		BOOL bQueryInfo = HttpQueryInfo(hRequest, HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER, 
										&lHttpStatus, &lHttpStatusSize, 0);
	
		if(bQueryInfo)
		{
			sMsg.Format(_T("Server response code: %ld"), lHttpStatus);
			m_Assync->SetProgress(sMsg, 0);
		}

		// Read HTTP response
		InternetReadFile(hRequest, pBuffer, 4095, &dwBuffSize);
		pBuffer[dwBuffSize] = 0;
		sMsg = CString((LPCSTR)pBuffer, dwBuffSize);
		sMsg = _T("Server response body:")  + sMsg;
		m_Assync->SetProgress(sMsg, 0);
	
		// If the first byte of HTTP response is a digit, than assume a legacy way
		// of determining delivery status - the HTTP response starts with a delivery status code
		if(dwBuffSize>0 && pBuffer[0]>='0' && pBuffer[0]<='9')
		{
			m_Assync->SetProgress(_T("Assuming legacy method of determining delivery status (from HTTP response body)."), 0);

			// Get status code from HTTP response
			if(atoi((LPCSTR)pBuffer)!=200)
			{
				m_Assync->SetProgress(_T("Failed (HTTP response body doesn't start with code 200)."), 100, false);
				goto cleanup;
			}

			break;
		}
		else
		{
			// If the first byte of HTTP response is not a digit, assume that
			// the delivery status should be read from HTTP header
		
			// Check if we have a redirect (302 response code)
			if(bQueryInfo && lHttpStatus==302)
			{	
				// Check for multiple redirects
				if(bRedirect)
				{
					m_Assync->SetProgress(_T("Multiple redirects are not allowed."), 100, false);
					goto cleanup;
				}

				bRedirect = TRUE;

				TCHAR szBuffer[1024]=_T("");
				DWORD dwBuffSize = sizeof(szBuffer)*sizeof(TCHAR);	
				DWORD nIndex = 0;				

				BOOL bQueryInfo = HttpQueryInfo(hRequest, HTTP_QUERY_LOCATION,
						szBuffer,
						&dwBuffSize,
						&nIndex);
				if(!bQueryInfo)
				{
					m_Assync->SetProgress(_T("Failed to redirect."), 100, false);
					goto cleanup;
				}
				else
				{
					// Parse the redirect URL
					ParseURL(szBuffer, szProtocol, 512, szServer, 512, dwPort, szURI, 1024);

					CString sMsg;
					sMsg.Format(_T("Redirecting to %s"), szBuffer);
					m_Assync->SetProgress(sMsg, 0, true);
					continue;
				}
			}

			// Check for server response code - expected code 200
			if(!bQueryInfo || lHttpStatus!=200)
			{
				m_Assync->SetProgress(_T("Failed (HTTP response code is not equal to 200)."), 100, false);
				goto cleanup;
			}
			
			break;
		}
	}

	// Add a message to log
    m_Assync->SetProgress(_T("Error report has been sent OK!"), 100, false);
    bStatus = TRUE;

cleanup:

    if(!bStatus)
    {
        // Add a message to log
        m_Assync->SetProgress(_T("Error sending HTTP request."), 100, false);
    }

    // Clean up
    if(hRequest) 
        InternetCloseHandle(hRequest);

    // Clean up internet handle
    if(hConnect) 
        InternetCloseHandle(hConnect);

    // Clean up internet session
    if(hSession) 
        InternetCloseHandle(hSession);

    // Notify about completion
    m_Assync->SetCompleted(bStatus?0:1);

    return bStatus;
}
Exemplo n.º 10
0
BOOL CHttpRequestSender::InternalSend()
{ 
  BOOL bStatus = FALSE;      // Resulting status
  strconv_t strconv;         // String conversion
  HINTERNET hSession = NULL; // Internet session
  HINTERNET hConnect = NULL; // Internet connection
  HINTERNET hRequest = NULL; // Handle to HTTP request
  TCHAR szProtocol[512];     // Protocol
  TCHAR szServer[512];       // Server name
  TCHAR szURI[1024];         // URI
  DWORD dwPort=0;            // Port
  CString sHeaders = _T("Content-type: multipart/form-data, boundary=") + m_sBoundary;
	LPCTSTR szAccept[2]={_T("*/*"), NULL};
  INTERNET_BUFFERS BufferIn;
	BYTE pBuffer[2048];
	BOOL bRet = FALSE;
  DWORD dwBuffSize = 0;
  CString sMsg;
  LONGLONG lPostSize = 0;  
  std::map<CString, std::string>::iterator it;
  std::map<CString, CHttpRequestFile>::iterator it2;

  // Calculate size of data to send
  m_Assync->SetProgress(_T("Calculating size of data to send."), 0);
  bRet = CalcRequestSize(lPostSize);
  if(!bRet)
  {
    m_Assync->SetProgress(_T("Error calculating size of data to send!"), 0);
    goto cleanup;
  }

  // Create Internet session
  m_Assync->SetProgress(_T("Opening Internet connection."), 0);
  hSession = InternetOpen(_T("CrashRpt"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	if(hSession==NULL)
  {
    m_Assync->SetProgress(_T("Error opening Internet session"), 0);
	  goto cleanup; 
  }
  
  // Parse application-provided URL
  ParseURL(m_Request.m_sUrl, szProtocol, 512, szServer, 512, dwPort, szURI, 1024);

  // Connect to HTTP server
  m_Assync->SetProgress(_T("Connecting to server"), 0, true);

  hConnect = InternetConnect(hSession, szServer, (WORD)dwPort, 
    NULL, NULL, INTERNET_SERVICE_HTTP, 0, 1);
	if(hConnect==NULL)
  {
    m_Assync->SetProgress(_T("Error connecting to server"), 0);
	  goto cleanup; 
  }

  if(m_Assync->IsCancelled()){ goto cleanup; }

  m_Assync->SetProgress(_T("Opening HTTP request..."), 0, true);

  hRequest = HttpOpenRequest(hConnect, _T("POST"), szURI, 
			NULL, NULL, szAccept, INTERNET_FLAG_NO_CACHE_WRITE, 0);
  if (!hRequest)
  {
	  m_Assync->SetProgress(_T("HttpOpenRequest has failed."), 0, true);
    goto cleanup;
  }
  
	BufferIn.dwStructSize = sizeof( INTERNET_BUFFERS ); // Must be set or error will occur
  BufferIn.Next = NULL; 
  BufferIn.lpcszHeader = sHeaders;
  BufferIn.dwHeadersLength = sHeaders.GetLength();
  BufferIn.dwHeadersTotal = 0;
  BufferIn.lpvBuffer = NULL;                
  BufferIn.dwBufferLength = 0;
  BufferIn.dwBufferTotal = (DWORD)lPostSize; // This is the only member used other than dwStructSize
  BufferIn.dwOffsetLow = 0;
  BufferIn.dwOffsetHigh = 0;

  m_dwPostSize = (DWORD)lPostSize;
  m_dwUploaded = 0;

  m_Assync->SetProgress(_T("Sending HTTP request..."), 0);
  if(!HttpSendRequestEx( hRequest, &BufferIn, NULL, 0, 0))
  {
    m_Assync->SetProgress(_T("HttpSendRequestEx has failed."), 0);
    goto cleanup;
  }

  // Write text fields
  for(it=m_Request.m_aTextFields.begin(); it!=m_Request.m_aTextFields.end(); it++)
  {
    bRet = WriteTextPart(hRequest, it->first); 
    if(!bRet)
      goto cleanup;
  }
	
  // Write attachments
  for(it2=m_Request.m_aIncludedFiles.begin(); it2!=m_Request.m_aIncludedFiles.end(); it2++)
  {
    bRet = WriteAttachmentPart(hRequest, it2->first); 
    if(!bRet)
      goto cleanup;
  }
	
  bRet = WriteTrailingBoundary(hRequest);
  if(!bRet)
    goto cleanup;

  m_Assync->SetProgress(_T("Ending HTTP request..."), 0);
  if(!HttpEndRequest(hRequest, NULL, 0, 0))
  {
    m_Assync->SetProgress(_T("HttpEndRequest has failed."), 0);
    goto cleanup;
  }

  m_Assync->SetProgress(_T("Reading server responce..."), 0);
  
  InternetReadFile(hRequest, pBuffer, 2048, &dwBuffSize);
  pBuffer[dwBuffSize] = 0;
  sMsg = CString((LPCSTR)pBuffer, dwBuffSize);
  sMsg = _T("Server returned:") + sMsg;
  m_Assync->SetProgress(sMsg, 0);
    
  if(atoi((LPCSTR)pBuffer)!=200)
  {
    m_Assync->SetProgress(_T("Failed."), 100, false);
    goto cleanup;
  }

  m_Assync->SetProgress(_T("Error report was sent OK!"), 100, false);
  bStatus = TRUE;

cleanup:

  if(!bStatus)
  {
    m_Assync->SetProgress(_T("Error sending HTTP request."), 100, false);
  }

  // Clean up
	if(hRequest) 
    InternetCloseHandle(hRequest);

	if(hConnect) 
    InternetCloseHandle(hConnect);

	if(hSession) 
    InternetCloseHandle(hSession);

  m_Assync->SetCompleted(bStatus?0:1);

  return bStatus;
}
Exemplo n.º 11
0
BOOL CHttpUploadFileProc::UseHttpSendReqEx(HINTERNET hRequest, CFile &file)
{
    //	生成form-data协议信息	<begin>
    CStringA	straHeader;
    CStringA	straContentHead;
    CStringA	straContentTail;

    straHeader = GetHttpAppendHeader();
    straContentHead = GetContentHead(file.GetFileName());
    straContentTail = GetContentTail();
    //	生成form-data协议信息	<end>

    ULONGLONG	ullFileLength = file.GetLength();
    DWORD	dwContentLength = straContentHead.GetLength() + (DWORD) ullFileLength + straContentTail.GetLength();

    INTERNET_BUFFERS BufferIn = {0};
    BufferIn.dwStructSize = sizeof( INTERNET_BUFFERS ); // Must be set or error will occur
    BufferIn.Next = NULL;
    //BufferIn.lpcszHeader = NULL;
    //BufferIn.dwHeadersLength = 0;
    BufferIn.lpcszHeader = straHeader.LockBuffer();
    straHeader.UnlockBuffer();
    BufferIn.dwHeadersLength = (DWORD)straHeader.GetLength();
    BufferIn.dwHeadersTotal = 0;
    BufferIn.lpvBuffer = NULL;
    BufferIn.dwBufferLength = 0;
    BufferIn.dwBufferTotal = dwContentLength;
    BufferIn.dwOffsetLow = 0;
    BufferIn.dwOffsetHigh = 0;

    if (IsTerminated())	return FALSE;
    NotifyReceiver(P_HUF_SENDING_FILE, 0);
    if(!HttpSendRequestEx( hRequest, &BufferIn, NULL, 0, 0))
        return FALSE;

    UINT	uProgressBegin = 10;
    UINT	uProgressEnd = 90;
    UINT	uProgressCur = 0;
    UINT	uReadCountSum = 0;


    const UINT uBufSize = 1024;
    BYTE pBuffer[uBufSize];
    UINT uReadCount;
    DWORD dwBytesWritten;
    BOOL bRet;
    float	fSendPercent;
    UINT	uProgressScale;


    //	Write Head
    bRet = InternetWriteFile( hRequest, straContentHead.LockBuffer(), straContentHead.GetLength(), &dwBytesWritten);
    straContentHead.UnlockBuffer();
    if(!bRet)
    {
        NotifyReceiver(E_HUF_SEND_FILE_FAILED, 0);
        return FALSE;
    }

    if (IsTerminated())	return FALSE;
    //	Write file contents
    uReadCountSum = 0;
    bRet = TRUE;
    file.SeekToBegin();
    do {
        if (IsTerminated())	return FALSE;
        uReadCount = file.Read(pBuffer, uBufSize);
        if (0 == uReadCount)
            break;

        if(! InternetWriteFile( hRequest, pBuffer, uReadCount, &dwBytesWritten))
        {
            NotifyReceiver(E_HUF_SEND_FILE_FAILED, 0);
            return FALSE;
        }

        uReadCountSum += uReadCount;
        fSendPercent = (float)uReadCountSum / BufferIn.dwBufferTotal;
        uProgressScale = (UINT) ((uProgressEnd - uProgressBegin) * fSendPercent);
        uProgressCur = uProgressBegin + uProgressScale;
        NotifyReceiver(P_HUF_PROGRESS, uProgressCur);

    } while (uReadCount == uBufSize);

    if (IsTerminated())	return FALSE;
    //	Write Tail
    bRet = InternetWriteFile( hRequest, straContentTail.LockBuffer(), straContentTail.GetLength(), &dwBytesWritten);
    straContentTail.UnlockBuffer();
    if(!bRet)
    {
        NotifyReceiver(E_HUF_SEND_FILE_FAILED, 0);
        return FALSE;
    }
    NotifyReceiver(P_HUF_PROGRESS, uProgressEnd);


    if (IsTerminated())	return FALSE;
    NotifyReceiver(P_HUF_WAIT_RESPONSE, 0);
    if (!HttpEndRequest(hRequest, NULL, 0, 0))
    {
        NotifyReceiver(E_HUF_WAIT_RESPONSE_FAILD, 0);
        bRet = FALSE;
    }

    return bRet;
}
Exemplo n.º 12
0
void ResourceHandle::onRequestComplete(LPARAM lParam)
{
    if (d->m_writing) {
        DWORD bytesWritten;
        InternetWriteFile(d->m_secondaryHandle,
                          d->m_formDataString + (d->m_formDataLength - d->m_bytesRemainingToWrite),
                          d->m_bytesRemainingToWrite,
                          &bytesWritten);
        d->m_bytesRemainingToWrite -= bytesWritten;
        if (!d->m_bytesRemainingToWrite) {
            // End the request.
            d->m_writing = false;
            HttpEndRequest(d->m_secondaryHandle, 0, 0, (DWORD_PTR)d->m_jobId);
            free(d->m_formDataString);
            d->m_formDataString = 0;
        }
        return;
    }

    HINTERNET handle = (method() == "POST") ? d->m_secondaryHandle : d->m_resourceHandle;
    BOOL ok = FALSE;

    static const int bufferSize = 32768;
    char buffer[bufferSize];
    INTERNET_BUFFERSA buffers;
    buffers.dwStructSize = sizeof(INTERNET_BUFFERSA);
    buffers.lpvBuffer = buffer;
    buffers.dwBufferLength = bufferSize;

    bool receivedAnyData = false;
    while ((ok = InternetReadFileExA(handle, &buffers, IRF_NO_WAIT, (DWORD_PTR)this)) && buffers.dwBufferLength) {
        if (!hasReceivedResponse()) {
            setHasReceivedResponse();
            ResourceResponse response;
            client()->didReceiveResponse(this, response);
        }
        client()->didReceiveData(this, buffer, buffers.dwBufferLength, 0);
        buffers.dwBufferLength = bufferSize;
    }

    PlatformDataStruct platformData;
    platformData.errorString = 0;
    platformData.error = 0;
    platformData.loaded = ok;

    if (!ok) {
        int error = GetLastError();
        if (error == ERROR_IO_PENDING)
            return;
        DWORD errorStringChars = 0;
        if (!InternetGetLastResponseInfo(&platformData.error, 0, &errorStringChars)) {
            if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
                platformData.errorString = new TCHAR[errorStringChars];
                InternetGetLastResponseInfo(&platformData.error, platformData.errorString, &errorStringChars);
            }
        }
        _RPTF1(_CRT_WARN, "Load error: %i\n", error);
    }
    
    if (d->m_secondaryHandle)
        InternetCloseHandle(d->m_secondaryHandle);
    InternetCloseHandle(d->m_resourceHandle);

    client()->didFinishLoading(this);
    delete this;
}
Exemplo n.º 13
0
BOOL CPostData::UseHttpSendReqEx( std::string& lpost)
{
	USES_CONVERSION;
	long lgg;					CString strtemp;
	lgg = lpost.size();

	INTERNET_BUFFERS BufferIn;
	DWORD dwBytesWritten;

	BOOL bRet;

	TCHAR head[1024];        
	std::wstring strt = MS_CONTENTTYPE;
	std::wstring strt1 = CA2W(CSNManager::GetInstance()->GetSN().c_str());
	//_stprintf_s(head, _countof(head), _T("%s\r\nSN: %s;\r\nMoneyhubuid: %s;\r\n"), strt.c_str() ,strt1.c_str() ,m_strHWID.c_str());
	_stprintf_s(head, _countof(head), _T("Sn: %s\r\nMoneyhubuid: %s\r\n"), strt1.c_str() ,m_strHWID.c_str());
	//TCHAR head[]= strt.c_str(); 

	BufferIn.dwStructSize = sizeof( INTERNET_BUFFERS ); // Must be set or error will occur
    BufferIn.Next = NULL; 
    BufferIn.lpcszHeader = head;
    BufferIn.dwHeadersLength = 0;
    BufferIn.dwHeadersTotal = sizeof(head);
    BufferIn.lpvBuffer = (LPSTR)lpost.c_str();                
    BufferIn.dwBufferLength = 0;
    BufferIn.dwBufferTotal = lgg; // This is the only member used other than dwStructSize
    BufferIn.dwOffsetLow = 0;
    BufferIn.dwOffsetHigh = 0;

	DWORD dwFlags = 0;
		DWORD dwBuffLen = sizeof(dwFlags);
		InternetQueryOption (m_hInetFile, INTERNET_OPTION_SECURITY_FLAGS,
			(LPVOID)&dwFlags, &dwBuffLen);

		dwFlags |=	(SECURITY_FLAG_IGNORE_UNKNOWN_CA | SECURITY_FLAG_IGNORE_CERT_CN_INVALID);
		InternetSetOption (m_hInetFile, INTERNET_OPTION_SECURITY_FLAGS, &dwFlags, sizeof (dwFlags) );

    if(!HttpSendRequestEx( m_hInetFile, &BufferIn, NULL, 0, 0))
    {
		strtemp.Format(_T("Error on HttpSendRequestEx %d\n"),GetLastError()); 
		int nLen = strtemp.GetLength();
		strt =strtemp.GetBuffer(nLen);
		strtemp.ReleaseBuffer();
		CRecordProgram::GetInstance()->RecordWarnInfo(MY_PRO_NAME, MY_COMMON_ERROR, strt);
		CRecordProgram::GetInstance()->RecordWarnInfo(MY_PRO_NAME, MY_COMMON_ERROR, L"HttpSendRequestEx");
		CloseHandles();
        printf( "Error on HttpSendRequestEx %d\n",GetLastError() );
        return FALSE;
    }

	bRet=TRUE;
	bRet = InternetWriteFile( m_hInetFile, (LPSTR)lpost.c_str(), lgg, &dwBytesWritten);

	if(!bRet)
	{
		strtemp.Format(_T("Error on HttpSendRequestEx %d\n"),GetLastError()); 
		int nLen = strtemp.GetLength();
		strt =strtemp.GetBuffer(nLen);
		strtemp.ReleaseBuffer();
		CRecordProgram::GetInstance()->RecordWarnInfo(MY_PRO_NAME, MY_COMMON_ERROR, strt);
		CRecordProgram::GetInstance()->RecordWarnInfo(MY_PRO_NAME, MY_COMMON_ERROR, L"HttpSendRequestEx  InternetWriteFile");
     	CloseHandles();
        printf( "\nError on InternetWriteFile %lu\n",GetLastError() );
        return FALSE;
    }

	bRet = HttpEndRequest(m_hInetFile, NULL, 0, 0);
    if(!bRet)
    {
		strtemp.Format(_T("Error on HttpSendRequestEx %d\n"),GetLastError()); 
		int nLen = strtemp.GetLength();
		strt =strtemp.GetBuffer(nLen);
		strtemp.ReleaseBuffer();
		CRecordProgram::GetInstance()->RecordWarnInfo(MY_PRO_NAME, MY_COMMON_ERROR, strt);
		CRecordProgram::GetInstance()->RecordWarnInfo(MY_PRO_NAME, MY_COMMON_ERROR, L"HttpSendRequestEx   HttpEndRequest");
    	CloseHandles();
        printf( "Error on HttpEndRequest %lu \n", GetLastError());
        return FALSE;
    }

		char pcBuffer[BUFFSIZE];
		DWORD dwBytesRead;
	    LPSTR	lpszData1;
		lpszData1 = new char[1024*1024];
		lpszData1[0]='\0';

		//printf("\nThe following was returned by the server:\n");
		do
		{	dwBytesRead=0;
			if(InternetReadFile(m_hInetFile, pcBuffer, BUFFSIZE-1, &dwBytesRead))
			{
				pcBuffer[dwBytesRead]=0x00; // Null-terminate buffer
        		strcat(lpszData1,pcBuffer);
				//printf("%s", pcBuffer);
			}
			else
                return FALSE;
				//lpszData1 ="";
				//printf("\nInternetReadFile failed");
		}while(dwBytesRead>0);
		//printf("\n");
		lpost = "";
		lpost = CW2A(UTF8ToUnicode(lpszData1).c_str());
	    delete []lpszData1;

	CloseHandles();
	//return  ERR_SUCCESS;
	return TRUE;
}
Exemplo n.º 14
0
int HttpConnection::request(InputStream& data, OutputStream& response, bool log_request)
{
    int readBytes = 0; 
    int totalBytesRead = 0;
    DWORD bytesWritten = 0;
    int ret = HTTP_STATUS_OK;
    WString headers;
    bool sendDataAtOnce = false;
    char *chunkToSend = NULL;
    int64_t contentLen = 0; 
    INTERNET_BUFFERS BufferIn = {0};
    DWORD errorCode = 0;
    char tmpbuff[1024];

#ifdef USE_ZLIB
    Bytef* cBuf = NULL;
    uLong  cBufLen  = 0;
    int64_t uncompressedContentLen = 0;
#endif
    
    // Timeout to receive a rensponse from server (default = 30 sec).
    DWORD reqTimeoutMsec = requestTimeout * 1000;
    DWORD resTimeoutMsec = responseTimeout == 0 ? 30 * 1000 : responseTimeout * 1000;
    InternetSetOption(req, INTERNET_OPTION_RECEIVE_TIMEOUT, &reqTimeoutMsec, sizeof(DWORD));
    InternetSetOption(req, INTERNET_OPTION_SEND_TIMEOUT,    &resTimeoutMsec, sizeof(DWORD));
    // InternetSetOption(req, SECURITY_FLAG_IGNORE_REVOCATION, NULL, 0);
    
    if (auth) {
        if (auth->getType() == HttpAuthentication::Basic) {
           StringBuffer authCred = auth->getAuthenticationHeaders();
           StringBuffer authHeader;
           authHeader.sprintf("Basic %s", authCred.c_str());

           setRequestHeader(HTTP_HEADER_AUTHORIZATION, authHeader);
        } else {
            LOG.error("%s: authentication type not supported [%d]", __FUNCTION__, auth->getType());
            return StatusInternalError;
        }
    }

    // For user agent, content length and accept encoding, override property
    // values, even if set by the caller.
    setRequestHeader(HTTP_HEADER_USER_AGENT, userAgent);
    
    contentLen = data.getTotalSize() - data.getPosition();

#ifdef USE_ZLIB
    if (compression_enabled) {
        chunkToSend = new char [contentLen];   

        if (data.read((void *)chunkToSend, contentLen) != contentLen) {
            LOG.error("error reading data from input stream");  
            delete [] chunkToSend;
            return StatusInternalError;
        }

        sendDataAtOnce = true;

        cBufLen = contentLen;

        // DEFLATE (compress data)
        cBuf =  new Bytef[contentLen];
 
        // compress the source buffer into the destination buffer.
        int err = compress(cBuf, &cBufLen, (Bytef*)chunkToSend, contentLen);

        if (err != Z_OK) {
            LOG.error("%s: error compressing data buffer [%d]", __FUNCTION__, err);

            setError(ERR_HTTP_DEFLATE, "ZLIB: error occurred compressing data.");
            delete [] chunkToSend;
            delete [] cBuf;

            return StatusInternalError;
        }
        
        uncompressedContentLen = contentLen;
        contentLen = cBufLen;

       
        sprintf(tmpbuff, "%llu", contentLen); 
        setRequestHeader(HTTP_HEADER_CONTENT_LENGTH, tmpbuff);
        setRequestHeader(HTTP_HEADER_ACCEPT_ENCODING, "deflate");
        setRequestHeader(HTTP_HEADER_CONTENT_ENCODING, "deflate");

        sprintf(tmpbuff, "%llu", uncompressedContentLen); 
        setRequestHeader(HTTP_HEADER_UNCOMPRESSED_CONTENT_LENGTH, tmpbuff);
    } else {
        sprintf(tmpbuff, "%llu", contentLen); 
        setRequestHeader(HTTP_HEADER_CONTENT_LENGTH, tmpbuff);
    }
#else
    sprintf(tmpbuff, "%llu", contentLen); 
    setRequestHeader(HTTP_HEADER_CONTENT_LENGTH, tmpbuff);
#endif

    writeHttpHeaders(headers);

    // header in the log are written in writeHttpHeaders function
    // LOG.debug("Request header:\n\n%ls", headers.c_str());

    // if the client allows to sync over https even if the server
    // has an invalid certificate, the flag is false. By default it is true
    //if (getSSLVerifyServer() == false) {
    /*DWORD extraSSLDwFlags = 0;
	DWORD dwBuffLen = sizeof(extraSSLDwFlags);
    extraSSLDwFlags |= SECURITY_FLAG_IGNORE_REVOCATION | SECURITY_FLAG_IGNORE_WRONG_USAGE 
                    | SECURITY_FLAG_IGNORE_CERT_CN_INVALID | SECURITY_FLAG_IGNORE_CERT_DATE_INVALID;

 	InternetSetOption (req, INTERNET_OPTION_SECURITY_FLAGS,
                         &extraSSLDwFlags, sizeof (extraSSLDwFlags) );
*/
    if (url.isSecure()) {
        DWORD dwFlags, dwBuffLen = sizeof(dwFlags);
        InternetQueryOption (req, INTERNET_OPTION_SECURITY_FLAGS, (LPVOID)&dwFlags, &dwBuffLen);    
        if (getSSLVerifyServer() == false) {            
            dwFlags |= SECURITY_FLAG_IGNORE_UNKNOWN_CA | SECURITY_FLAG_IGNORE_REVOCATION | SECURITY_FLAG_IGNORE_WRONG_USAGE 
                    | SECURITY_FLAG_IGNORE_CERT_CN_INVALID | SECURITY_FLAG_IGNORE_CERT_DATE_INVALID;
            
        } else {
             dwFlags = dwFlags| INTERNET_FLAG_SECURE;
        }
        InternetSetOption (req, INTERNET_OPTION_SECURITY_FLAGS, &dwFlags, sizeof (dwFlags));     
    }
     
    bool retry = false;

    // give a chance to submit again if error is ERROR_INTERNET_SEC_CERT_REV_FAILED
    bool retryFlagRevocation = true;

    BufferIn.dwStructSize = sizeof( INTERNET_BUFFERS ); // Must be set or error will occur
    BufferIn.Next = NULL;
    BufferIn.lpcszHeader = headers.c_str();
    BufferIn.dwHeadersLength = headers.length(); 
    BufferIn.dwHeadersTotal = 0;
    BufferIn.lpvBuffer = NULL;
    BufferIn.dwBufferLength = 0;
    BufferIn.dwBufferTotal = 0; //contentLen;
    BufferIn.dwOffsetLow = 0;
    BufferIn.dwOffsetHigh = 0;

    do {
        retry = false;
        if (!HttpSendRequestEx(req, &BufferIn, NULL, HSR_INITIATE, 0)) {
            DWORD err = GetLastError();
            if (err == ERROR_INTERNET_SEC_CERT_REV_FAILED && retryFlagRevocation) {
                LOG.info("%s: error ERROR_INTERNET_SEC_CERT_REV_FAILED: retry once a time", __FUNCTION__);
                DWORD dwFlags, dwBuffLen = sizeof(dwFlags);
                InternetQueryOption (req, INTERNET_OPTION_SECURITY_FLAGS, (LPVOID)&dwFlags, &dwBuffLen);    
                dwFlags |= SECURITY_FLAG_IGNORE_REVOCATION;
                InternetSetOption (req, INTERNET_OPTION_SECURITY_FLAGS, &dwFlags, sizeof (dwFlags));    
                retryFlagRevocation = false;
                retry = true;
                continue;
            }
                
            const char* msg = createHttpErrorMessage(err);
            LOG.error("HttpSendRequestEx failed: code %d: %s", err, msg);
            delete [] msg;
            return StatusNetworkError;
        }

#ifdef USE_ZLIB
        if (compression_enabled) {        
            if (sendData((const char *)cBuf, cBufLen) != 0) {
                delete [] cBuf;
                delete [] chunkToSend;

                return StatusWritingError;
            }

            delete [] cBuf;
        }
#endif

        if (!sendDataAtOnce) {
            int64_t bufferSize = std::min(requestChunkSize, contentLen);
            chunkToSend = new char[bufferSize+1];   

            while ((readBytes = data.read((void *)chunkToSend, bufferSize))) {
                if (sendData(chunkToSend, readBytes) != 0) {
                    delete [] chunkToSend;
                    return StatusWritingError;
                }
                fireTransportEvent(readBytes, DATA_SENT);
            }
        }

        delete [] chunkToSend;
	
	    if (data.error()) {
		    LOG.error("[%s] Input stream read error: %d on %d bytes read", __FUNCTION__, data.getPosition(), data.getTotalSize());
		    return StatusStreamReadingError;
	    }

        if (!HttpEndRequest(req, NULL, 0, 0)) {
            DWORD err = GetLastError();
            const char* msg = createHttpErrorMessage(err);
            LOG.error("HttpEndRequest failed: code %d: %s", err, msg);
            delete [] msg;
            return StatusNetworkError;
        }

        readResponseHeaders();

        ret = checkResponseStatus(); 
        if (ret == ERROR_INTERNET_FORCE_RETRY) {
            retry = true;
        }

    } while (retry == true);

    if (isErrorStatus(ret)) {      
        return ret;
    }
   
    StringBuffer nullval(NULL);
    if ((getRequestHeaders().get(HTTP_HEADER_RANGE) != nullval) && ret == 200) {
        // it means the client asks a partial response but the server doesn't support it.
        // the right answer from server is HTTP 206
        LOG.info("%s: client asks a Range, but server responds 200 instead of 206 (Partial Content). Reset the outputstream and start from scratch.", __FUNCTION__);
        response.reset();
    }

    if (readResponse(response) != 0) {
        return StatusReadingError;
    }

    return ret;
}
Exemplo n.º 15
0
BOOL baidu_upload(CString sfile, CString token, CString fname,DWORD *process)
{
	if (sfile == L"")
	{
		MessageBox(NULL, L"Îļþ·¾¶²»ÄÜΪ¿Õ", 0, 0);
		return FALSE;
	}
	if (token == L"")
	{
		MessageBox(NULL, L"token²»ÄÜΪ¿Õ", 0, 0);
		return FALSE;
	}
	if (fname == L"")
	{
		MessageBox(NULL, L"ÎļþÃû²»ÄÜΪ¿Õ", 0, 0);
		return FALSE;
	}

	CString url(L"/rest/2.0/pcs/file?method=upload&ondup=overwrite&path=%2Fapps%2Fhitdisk%2F" + fname + L"&access_token=" + token);

	DWORD total_length = 0;//ÉÏ´«Êý¾Ý×Ü´óС
	DWORD file_length = 0;//ÉÏ´«ÎļþµÄ´óС
	//DWORD read_length = 0;//ÒѾ­´ÓÎļþ¶ÁÈ¡µÄ´óС
	DWORD sent_length = 0;//ÒѾ­ÉÏ´«µÄÎļþµÄ´óС

	DWORD sent_bfleng = 0;//µ±Ç°Êý¾Ý¿éÒÑÉÏ´«´óС

	DWORD head_length = 0;//Êý¾ÝÍ·´óС
	DWORD tail_length = 0;//Êý¾Ýβ´óС



	DWORD read_part = 1024 * 1024 * 2;
	DWORD send_part = 1024;

	DWORD read_tmp = 0;//µ±Ç°´ÓÎļþ¶ÁÈ¡µ½»º³åÇøµÄ´óС
	DWORD sent_tmp = 0;//µ±Ç°·¢ËÍ´óС


	CFile cfile(sfile, CFile::modeRead);
	file_length = (DWORD)cfile.GetLength();
	CHAR *send_buffer = new CHAR[read_part];


	HINTERNET hRequest = NULL;
	HINTERNET hConnect = NULL;
	HINTERNET hnet = InternetOpen(fname, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);

	hConnect = InternetConnect(hnet, L"pcs.baidu.com", 443, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);
	hRequest = HttpOpenRequest(hConnect, L"POST", url, NULL, NULL, NULL, INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP | INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_NO_AUTH | INTERNET_FLAG_NO_COOKIES | INTERNET_FLAG_NO_UI | INTERNET_FLAG_SECURE | INTERNET_FLAG_IGNORE_CERT_CN_INVALID | INTERNET_FLAG_RELOAD, 0);

	TCHAR ct[] = L"Content-Type: multipart/form-data; boundary=--myself";
	HttpAddRequestHeaders(hRequest, ct, lstrlen(ct), HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE);


	CHAR head[] = "----myself\r\nContent-Disposition: form-data; name=\"file\"; filename=\"\"\r\n\r\n";
	CHAR tail[] = "\r\n----myself--\r\n";
	head_length = strlen(head);
	tail_length = strlen(tail);

	total_length = file_length + head_length + tail_length;

	INTERNET_BUFFERS Ibuffer;
	ZeroMemory(&Ibuffer, sizeof(INTERNET_BUFFERS));
	Ibuffer.dwBufferTotal = total_length;
	Ibuffer.dwStructSize = sizeof(INTERNET_BUFFERS);

	HttpSendRequestEx(hRequest, &Ibuffer, NULL, 0, NULL);

	InternetWriteFile(hRequest, head, head_length, &sent_tmp);
	sent_length += sent_tmp;

	while (read_tmp = cfile.Read(send_buffer, read_part))
	{
		sent_bfleng = 0;
		while (sent_bfleng != read_tmp)
		{
			if (read_tmp - sent_bfleng > send_part)
			{
				InternetWriteFile(hRequest, send_buffer + sent_bfleng, send_part, &sent_tmp);
			}
			else
			{
				InternetWriteFile(hRequest, send_buffer + sent_bfleng, read_tmp - sent_bfleng, &sent_tmp);
			}
			if (sent_tmp == 0)
			{
				InternetCloseHandle(hRequest);
				InternetCloseHandle(hConnect);
				InternetCloseHandle(hnet);
				cfile.Close();
				delete[] send_buffer;
				return FALSE;
			}
			sent_bfleng += sent_tmp;
			sent_length += sent_tmp;
			*process = (DWORD)(100 * (double)sent_length / total_length);
		}
	}

	InternetWriteFile(hRequest, tail, tail_length, &sent_tmp);
	sent_length += sent_tmp;
	*process = (DWORD)(100 * (double)sent_length / total_length);

	HttpEndRequest(hRequest, NULL, 0, NULL);
	InternetCloseHandle(hRequest);
	InternetCloseHandle(hConnect);
	InternetCloseHandle(hnet);
	cfile.Close();
	delete[] send_buffer;


	return TRUE;

}
Exemplo n.º 16
0
BOOL vmsPostRequest::Send(LPCTSTR ptszServer, LPCTSTR ptszFilePath, LPCVOID pvData, DWORD dwDataSize, LPCTSTR ptszContentType, std::string *pstrResponse)
{
	Close ();

	DWORD dwAccessType = INTERNET_OPEN_TYPE_PRECONFIG;
	if (m_pProxyInfo)
		dwAccessType = m_pProxyInfo->tstrAddr.empty () ? INTERNET_OPEN_TYPE_DIRECT : INTERNET_OPEN_TYPE_PROXY;
	m_hInet = InternetOpen (m_tstrUserAgent.c_str (), dwAccessType,
		dwAccessType == INTERNET_OPEN_TYPE_PROXY ? m_pProxyInfo->tstrAddr.c_str () : NULL, NULL, 0);
	if (m_hInet == NULL)
		return FALSE;

	PostInitWinInetHandle (m_hInet);

	m_hConnect = InternetConnect (m_hInet, ptszServer, INTERNET_DEFAULT_HTTP_PORT, 
		NULL, NULL, INTERNET_SERVICE_HTTP, 0, NULL);
	if (m_hConnect == NULL)
		return FALSE;

#ifdef DEBUG_SHOW_SERVER_REQUESTS
	TCHAR tszTmpPath [MAX_PATH];
	GetTempPath (MAX_PATH, tszTmpPath);
	TCHAR tszTmpFile [MAX_PATH];
	_stprintf (tszTmpFile, _T ("%s\\si_serv_req_%d.txt"), tszTmpPath, _c++);
	HANDLE hLog = CreateFile (tszTmpFile, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
	DWORD dwLogWritten;
	#define LOG_REQ(s) WriteFile (hLog, s, strlen (s), &dwLogWritten, NULL)
	#define LOG_REQ_OPEN	CloseHandle (hLog); ShellExecute (NULL, "open", tszTmpFile, NULL, NULL, SW_SHOW);
	char szTmp [10000] = ""; DWORD dwTmp = 10000;
	#define LOG_REQ_HTTP_HDRS *szTmp = 0; HttpQueryInfo (m_hRequest, HTTP_QUERY_RAW_HEADERS_CRLF | HTTP_QUERY_FLAG_REQUEST_HEADERS, szTmp, &dwTmp, 0); LOG_REQ (szTmp);
	#define LOG_REQ_ALL LOG_REQ_HTTP_HDRS; LOG_REQ ((LPCSTR)pvData);
	#define LOG_RESP_HTTP_HDRS *szTmp = 0; HttpQueryInfo (m_hRequest, HTTP_QUERY_RAW_HEADERS_CRLF, szTmp, &dwTmp, 0); LOG_REQ (szTmp);
	DWORD dwErr;
#else
	#define LOG_REQ(s) 
	#define LOG_REQ_OPEN
	#define LOG_REQ_HTTP_HDRS
	#define LOG_RESP_HTTP_HDRS
	#define LOG_REQ_ALL
#endif

	m_hRequest = HttpOpenRequest (m_hConnect, _T ("POST"), ptszFilePath, NULL, NULL, NULL,
		INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_NO_UI | 
		INTERNET_FLAG_PRAGMA_NOCACHE, 0);
	if (m_hRequest == NULL)
	{
		DWORD dwErr = GetLastError ();
		LOG_REQ ("SERVER FAILURE\r\n");
		LOG_REQ_OPEN;
		SetLastError (dwErr);
		return FALSE;
	}

	ApplyProxyAuth (m_hRequest);

	if (ptszContentType)
	{
		tstring tstr = _T ("Content-Type: ");
		tstr += ptszContentType;
		tstr += _T ("\r\n");
		HttpAddRequestHeaders (m_hRequest, tstr.c_str (), tstr.length (), HTTP_ADDREQ_FLAG_ADD|HTTP_ADDREQ_FLAG_REPLACE);
	}

#ifdef vmsPostRequest_USE_NO_HTTPSENDREQUESTEX
	if (FALSE == HttpSendRequest (m_hRequest, NULL, 0, (LPVOID)pvData, dwDataSize))
		return FALSE;
#else
	INTERNET_BUFFERS buffs;
	ZeroMemory (&buffs, sizeof (buffs));
	buffs.dwStructSize = sizeof (buffs);
	buffs.dwBufferTotal = dwDataSize;

	if (FALSE == HttpSendRequestEx (m_hRequest, &buffs, NULL, 0, 0))
	{
		PUL (" >>> HttpSendRequestEx failed.");
		LOG_REQ ("SERVER FAILURE\r\n");
		LOG_REQ_OPEN;
		return FALSE;
	}

	if (FALSE == MyInternetWriteFile (m_hRequest, pvData, dwDataSize))
	{
		PUL (" >>> MyInternetWriteFile failed.");
		LOG_REQ ("SERVER FAILURE\r\n");
		LOG_REQ_OPEN;
		return FALSE;
	}

	if (FALSE == HttpEndRequest (m_hRequest, NULL, 0, 0))
	{
		PUL (" >>> HttpEndRequest failed.");
		LOG_REQ_ALL;
		LOG_REQ ("\r\n\r\n");
		LOG_RESP_HTTP_HDRS;
		LOG_REQ ("SERVER FAILURE\r\n");
		LOG_REQ_OPEN;
		return FALSE;
	}
#endif

	LOG_REQ_ALL;
	LOG_REQ ("\r\n\r\n");
	LOG_RESP_HTTP_HDRS;

	if (pstrResponse)
	{
		*pstrResponse = "";
		char sz [1025];
		DWORD dw;		
		while (InternetReadFile (m_hRequest, sz, sizeof (sz) - 1, &dw) && dw != 0)
		{
			sz [dw] = 0;
			(*pstrResponse) += sz;
		}
	}

	LOG_REQ_OPEN;
	return TRUE;
}
Exemplo n.º 17
0
Arquivo: swas.cpp Projeto: Kerogi/swas
bool SendFile(HANDLE hFile, const TCHAR* sUrl, const char* sVariableName, const char* sFileName) {
	if(!hFile) return false;
	bool result = false;
	LARGE_INTEGER lnSize;
	if(!GetFileSizeEx(hFile, &lnSize)){
		CloseHandle(hFile);
		return false;
	}
	DWORD nDataSize = lnSize.LowPart;
	if(!(nDataSize>0)) {
		CloseHandle(hFile);
		return false;
	}
	std::vector<char> pData(nDataSize);
	DWORD nReadSize = 0; 
	if(!ReadFile(hFile, (void*)&pData[0], nDataSize, &nReadSize, NULL) || !(nReadSize >0) || (nReadSize != nDataSize)) {
		CloseHandle(hFile);
		return false;
	}
	CloseHandle(hFile);

	TCHAR extraInfo[URL_PART_SIZE];
	TCHAR hostName[URL_PART_SIZE];
	TCHAR passwordSet[URL_PART_SIZE];
	TCHAR schemeUrl[URL_PART_SIZE];
	TCHAR fileUrlPath[URL_PART_SIZE];
	TCHAR userName[URL_PART_SIZE];

	URL_COMPONENTS aUrl;
	aUrl.dwStructSize=sizeof(URL_COMPONENTS);
	aUrl.dwHostNameLength=URL_PART_SIZE;
	aUrl.dwPasswordLength=URL_PART_SIZE;
	aUrl.dwSchemeLength=URL_PART_SIZE;
	aUrl.dwUrlPathLength=URL_PART_SIZE;
	aUrl.dwUserNameLength=URL_PART_SIZE;
	aUrl.dwExtraInfoLength=URL_PART_SIZE;
	aUrl.lpszExtraInfo=extraInfo;
	aUrl.lpszHostName=hostName;
	aUrl.lpszPassword=passwordSet;
	aUrl.lpszScheme=schemeUrl;
	aUrl.lpszUrlPath=fileUrlPath;
	aUrl.lpszUserName=userName;

	PCTSTR rgpszAcceptTypes[] = {_T("text/*"), NULL};

	if(!InternetCrackUrl(sUrl, 0, 0, &aUrl)) return false;
	HINTERNET hInternet = InternetOpen(TEXT("swas"),INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	if(hInternet) {
		HINTERNET hConnect = InternetConnect(hInternet,aUrl.lpszHostName, aUrl.nPort, aUrl.lpszUserName, aUrl.lpszHostName, INTERNET_SERVICE_HTTP, 0, 0);
		if(hConnect){
			HINTERNET hReq = HttpOpenRequest(hConnect, TEXT("POST"), aUrl.lpszUrlPath, NULL, NULL, rgpszAcceptTypes, 
				INTERNET_FLAG_NO_UI | INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_RELOAD, 0);
			if(hReq) {
				

				//see http://stackoverflow.com/questions/6407755/how-to-send-a-zip-file-using-wininet-in-my-vc-application
				char sBoundary[HEADERS_MAX_SIZE];
				if(GenerateBoundary(sBoundary, HEADERS_MAX_SIZE, sFileName)) {
					std::stringstream osHeaders;
					std::stringstream osHeadPart;
					std::stringstream osTailPart;
					const char const endl[] = "\r\n"; 

					osHeaders<<"Content-Type: multipart/form-data; boundary="<<sBoundary;

					osHeadPart<<"--"<<sBoundary<<endl;
					osHeadPart<<"Content-Disposition: form-data; ";
					osHeadPart<<"name=\""<<((NULL != sVariableName)?sVariableName:"filearg")<<"\"; ";
					osHeadPart<<"filename=\""<<((NULL != sFileName)?sFileName:"Chrome Tabs")<<"\""<<endl;
					osHeadPart<<"Content-Type: application/octet-stream"<<endl;
					osHeadPart<<endl;

					osTailPart<<endl<<"--"<<sBoundary<<"--"<<endl;

					std::string sHeaders = osHeaders.str();
					std::string sHeadPart = osHeadPart.str();
					std::string sTailPart = osTailPart.str();

					HttpAddRequestHeadersA(hReq, sHeaders.c_str(), -1, HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD); 
				
					INTERNET_BUFFERS bufferIn;

					memset(&bufferIn, 0, sizeof(INTERNET_BUFFERS));

					bufferIn.dwStructSize  = sizeof(INTERNET_BUFFERS);
					bufferIn.dwBufferTotal = sHeadPart.length() + nDataSize + sTailPart.length();
					DWORD bytesWritten;
					if(HttpSendRequestEx(hReq, &bufferIn, NULL, HSR_INITIATE, 0)) {
						InternetWriteFile(hReq, (const void*)sHeadPart.c_str(), sHeadPart.length(), &bytesWritten);

						InternetWriteFile(hReq, (const void*)&pData[0], nDataSize, &bytesWritten);
						// or a while loop for call InternetWriteFile every 1024 bytes...

						InternetWriteFile(hReq, (const void*)sTailPart.c_str(), sTailPart.length(), &bytesWritten);
						result = true;
					}else{
						ShowAnError(GetLastError(), TEXT("Network error"), TEXT("Wininet"));
					}
				}
				HttpEndRequest(hReq, NULL, HSR_INITIATE, 0);

			}else{
				ShowAnError(GetLastError(), TEXT("Network error"), TEXT("Wininet"));
			}
		}else{
			ShowAnError(GetLastError(), TEXT("Network error"), TEXT("Wininet"));
		}
		InternetCloseHandle(hInternet);
	}
	return result;
}