Jump to content

Random C++ Questions


Chance
 Share

Recommended Posts

LPCTSTR szContentType = TEXT("Content-Type: application/x-www-form-urlencoded\r\n");
szContentType &= TEXT("Test-Data: testinfo\r\n");//usually how I'm used to doing it in AutoIt :P

How do I do this correctly in C/C++?

I basically just want to append header info to the header variable szContentType.

The problem is that I don't want to have to make my headers info into one really long line, and since I still know very little about variable types and conversion methods in C++, this is pretty hard for me...

LPCTSTR szContentType=TEXT("Content-Type: application/x-www-form-urlencoded\r\nTest-Data: nothinghere\r\nSomething-Else: infohere;q=0.9,*;q=0");

if(!::HttpSendRequest( _hHTTPRequest, // handle by returned HttpOpenRequest
         szContentType, // additional HTTP header
         _tcslen(szContentType), // additional HTTP header length
         (LPVOID)szPostArguments, // additional data in HTTP Post or HTTP Put
         _tcslen(szPostArguments)// additional data length
     )
){
     //HTTPApp::Close();
return FALSE;
}
Edited by DeputyDerp
Link to comment
Share on other sites

Use somethng like this in C:

char szContentType[200] = TEXT("Content-Type: application/x-www-form-urlencodedrn");
    strcat(szContentType, TEXT("Test-Data: testinforn"));

Edit: Or use String-Class in C++

Edited by funkey

Programming today is a race between software engineers striving to
build bigger and better idiot-proof programs, and the Universe
trying to produce bigger and better idiots.
So far, the Universe is winning.

Link to comment
Share on other sites

Use somethng like this in C:

char szContentType[200] = TEXT("Content-Type: application/x-www-form-urlencoded\r\n");
    strcat(szContentType, TEXT("Test-Data: testinfo\r\n"));

Edit: Or use String-Class in C++

Ha, yes, this is what I found a little while ago and started using, makes things a lot easier.

Now I'm just having a few problems with wininet atm.

Also, thanks JohnOne, that lead me to an a page that explained things like this pretty well.

My other problem is now with this bit~

BOOL Stats =::HttpSendRequest(
         _hHTTPRequest,
         szContentType, // this is the variable I was trying to manage and successfully did using strcat()
         _tcslen(szContentType),
         (LPVOID)szEscapedURL, // this is another variable I was trying to manage and successfully did using strcat()
         _tcslen(szEscapedURL)
);

if(!Stats){
HTTPApp::Close();//for some reason, Stats is always false, but iff I comment out this code that closes the connection, the POST request is compleated with success even though Stats returned false
return FALSE;
}

Basically, I'm just trying t understand why HttpSendRequest keeps returning a bool of FALSE causing the if statment to fall through and close all connection, yet, if I actually remove the if statment to prevent the connection being closed, the request is actually compleated successfully.

It also works if I add a sleep(1000), but BOOL Stats still returns FALSE value :<

Edited by DeputyDerp
Link to comment
Share on other sites

You should call GetLastError for more info.

Thanks, I added this code~

BOOL Stats =::HttpSendRequest(
            _hHTTPRequest, 
            NULL,
            -1L, 
            NULL,
            0
    );

    Sleep(1000);

if(!Stats){
    _dwError=::GetLastError();

#ifdef _DEBUG
    LPVOID     lpMsgBuffer;
    DWORD dwRet=FormatMessage(
                FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
                NULL,
                ::GetLastError(),
                MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                reinterpret_cast<LPTSTR>(&lpMsgBuffer),
                0,
                NULL
[size=4]    );[/size]
    TRACE("n%d : %sn", _dwError, reinterpret_cast<LPTSTR>(lpMsgBuffer));
    LocalFree(lpMsgBuffer);
#endif

        TCHAR ReturnValue[100];
        StringCbPrintf(ReturnValue, 100, TEXT("%d"), _dwError);
        MessageBox(0, ReturnValue, "Error Code:", MB_ICONINFORMATION | MB_OK);// Returns 997

        //HTTPApp::Close();
return FALSE;
}

The last error is returned is 997

and I ran codeblocks debugger to get the message thing, and it gives this...

Building to ensure sources are up-to-date
Build succeeded
Selecting target:
Debug
Adding source dir: C:Documents and SettingsScriptKittyDesktopTest UI
Adding source dir: C:Documents and SettingsScriptKittyDesktopTest UI
Adding file: binDebugTest UI.exe
Starting debugger:
done
Registered new type: wxString
Registered new type: STL String
Registered new type: STL Vector
Setting breakpoints
(no debugging symbols found)
Debugger name and version: GNU gdb 6.8
Child process PID: 4560
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
Program received signal SIGSEGV, Segmentation fault. <-- i think this has something to do with it...
In lstrlenA () (C:WINDOWSsystem32kernel32.dll)
Continuing...
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
Program exited normally.
Debugger finished with status 0

Also, I found out about Strsafe.h and downloaded the header and used StringCchCopyA and StringCchCatA instead.

Link to comment
Share on other sites

Am I to understand that you're doing Windows programming in Code::Blocks?

Yes, is this a bad thing?

Error 997 it means: Overlapped I/O operation is in progress.

What flag are you use as parameter for InternetOpen() function?

How strange...

Switching from this flag

_hHTTPOpen =::InternetOpen(
     szAgent,
     INTERNET_OPEN_TYPE_DIRECT,
     NULL,
     NULL,
     INTERNET_FLAG_ASYNC
);

to this

_hHTTPOpen =::InternetOpen(
     szAgent,
     INTERNET_OPEN_TYPE_DIRECT,
     NULL,
     NULL,
     0
);

Prevented the function from just exiting and falling through.. I guess that option makes the request happen in the background or something, and I needed it to stick around and wait till if finished.

I guess I should have been paying more attention to those flags. >INTERNET_FLAG_ASYNC

Edited by DeputyDerp
Link to comment
Share on other sites

I wouldn't call it a bad thing. Just seems like VisualStudio is the way to go for Windows programming. But don't quote me. I'm no expert.

I get that a lot. It's just that I'm more familiar with codeblocks since I've been playing around with it since I was 13 or 14, I have MVS 2010 E but I have trouble porting one project to the other. For instance, I have one function that's compatable with MVS that declares variables using the statment "string", and I get an error on simple things like that when I try compiling with MinGW or GCC. I'm still trying to learn these things.

Link to comment
Share on other sites

Overlapped I/O is just asynchronous I/O. You need to check for the status over time until it reports being finished.

Yes, thank you.

I'm not on that level yet to successfully make use of that method, I'm just playing around with sending POST and GET requests to a makeshift Apache server I'm using to test apps like this, I'm basically trying to replicate this AutoIt function and convert it to C++ so I can easily use it in my C++ projects...

But as I found, code::bloxs doesn't have a winhttp.h header I can use and only wininet.h, so I've been trying to use wininet since supprisingly it lets me handle cookies too unlike winhttp.

#include "WinHttp.au3"; you need WinHTTP
#Include "ZLIB.au3"; and ZLIB http://www.autoitscript.com/forum/topic/128962-zlib-deflateinflategzip-udf/

OnAutoItExitRegister("_TerminateSession")

Global $_WinHTTP_CurrentSession[2] = [ -1, -1]

Global $sURL = "http://www.worldwideweb.com"

$Return = _WinHTTP_Action($sURL, "GET")
Switch @error
    Case 0
        ConsoleWrite( _
            "+=====HEADER====+" & @CRLF & _
            $Return[1] & @CRLF & _
            "-===== HTML ====-" & @CRLF & _
            BinaryToString($Return[0]) & @CRLF _
        )
    Case 1
        MsgBox(48, "Error!", "WinHTTP is not available on your system!")

    Case 2
        MsgBox(16, "Error!", "You need to supply a URL :P")

    Case 3
        MsgBox(16, "Error!", "Error cracking URL! URL might be invlaid.")

    Case 4
        MsgBox(16, "Error!", "Error creating session!")

    Case 5
        MsgBox(16, "Error!", "Error in connecting to website!")

    Case 6
        MsgBox(16, "Error!", "Error in creating request!")

    Case 7
        MsgBox(16, "Error!", "Unable to send request correctly.")

    Case 8
        MsgBox(16, "Error!", "Website did not respond.")

    Case 9
        MsgBox(16, "Error!", "No data was avaiable from the request :/")

EndSwitch
Exit


; #FUNCTION# ====================================================================================================================
; Name ..........: _WinHTTP_Action
; Description ...:
; Syntax ........: _WinHTTP_Action($Page[, $Action = Default[, $bBinary = Default[, $sUserAgent = Default[, $headers = Default[,
;                  $AdditionalData = Default[, $ReadReturn = Default[, $sReferer = Default[, $Proxy = Default[,
;                  $SessionDur = Default]]]]]]]]])
; Parameters ....: $Page                - String value of internet resource
;
;                  $Action              - [optional] HTTP verb to use in the request. Default is "GET".
;
;                  $bBinary             - [optional] A bool value. Default is False, which returns data as text.
;                                            | True returns binary, such as a file on the internet, like an exe.
;
;                  $sUserAgent          - [optional] A string value. Default is a GoogleBot user-agent string.
;                                            | A GoogleBot user-agent is used because sometimes it allows you to bypass
;                                            | a websites login requests, sites do this to optimize websearch results for their
;                                            | sites so we take advantage of this little trick.
;
;                  $headers             - [optional] A string value. Default is to accept all, keep alive and request
;                                           | compressed gzip encoding to reduce load.
;
;                  $AdditionalData      - [optional] A string value. Default is nothing, this is where you typically send
;                                             | the target server some arguments/variables or other stuff.
;
;                  $ReadReturn          - [optional] An bool value. Default is True and will return response headers and
;                                            | data in an array. False will just make the POST or GET request and come back.
;
;                  $sReferer            - [optional] A string value. Default is nothing I think.
;
;                  $Proxy               - [optional] A string value. Default is not to use a proxy, if you want to use a proxy
;                                            | then just put it in like "123.123.123.123:54321".
;
;                  $SessionDur          - [optional] An int value. Default is 60000 miliseconds which is 60 seconds.
;                                            | this is used to tell the function how long this session is supposed to last
;                                            | while this function is not called for an extended time.
;                                            | is this value is zero (0), the session is terminated upon compleation...
;
; Return values .: An array.
;                    0|HTML
;                    1|Responce Headers
;
; Author ........: ScriptKitty
; Remarks .......: This function will automatically handle compressed data, charset type, session, http/https access
; Example .......: No
; ===============================================================================================================================
Func _WinHTTP_Action( _
        $Page, _
        $Action = Default, _
        $bBinary = Default, _
        $sUserAgent = Default, _
        $headers = Default, _
        $AdditionalData = Default, _
        $ReadReturn = Default, _
        $sReferer = Default, _
        $Proxy = Default, _
        $SessionDur = Default _
        )

    Local $DefHeaders = _
            "Connection: Keep-alive" & @CRLF & _
            "Accept: */*" & @CRLF & _
            "Accept-Encoding: gzip;q=1,*;q=0" & @CRLF

    __WinHttpDefault($Action, "GET")
    __WinHttpDefault($bBinary, False)
    __WinHttpDefault($sUserAgent, "Googlebot/2.1 (+http://www.google.com/bot.html)")
    __WinHttpDefault($headers, $DefHeaders)
    __WinHttpDefault($ReadReturn, True)
    __WinHttpDefault($SessionDur, 60000)
    __WinHttpDefault($Proxy, False)

    If ($_WinHTTP_CurrentSession[1] <> 1) Then
        If Not _WinHttpCheckPlatform() Then Return SetError(1, 0, 0)
        $_WinHTTP_CurrentSession[1] = 1
    EndIf

    If Not $Page Then Return SetError(2, 0, 0)

    Local $Crack = _WinHttpCrackUrl($Page)
    If @error Then Return SetError(3, 0, 0)

    Local $Port = $INTERNET_DEFAULT_PORT
    Local $Flag
    Local $iCharset = 0

    If Not $Crack[0] Then $Crack[0] = "https"

    If StringLower($Crack[0]) == "http" Then
        $Port = $INTERNET_DEFAULT_HTTP_PORT
        $Flag = Default
    ElseIf StringLower($Crack[0]) == "https" Then
        $Port = $INTERNET_DEFAULT_HTTPS_PORT
        $Flag = $WINHTTP_FLAG_SECURE
    EndIf

    If ($_WinHTTP_CurrentSession[0] = -1) Then
        If $Proxy Then
            $_WinHTTP_CurrentSession[0] = _WinHttpOpen($sUserAgent, $WINHTTP_ACCESS_TYPE_NAMED_PROXY, $Proxy)
        Else
            $_WinHTTP_CurrentSession[0] = _WinHttpOpen($sUserAgent)
        EndIf
        If @error Then
            $_WinHTTP_CurrentSession[0] = -1
            Return SetError(4, 0, 0)
        EndIf
    EndIf

    AdlibRegister("_TerminateSession", $SessionDur)

    Local $hConnect = _WinHttpConnect($_WinHTTP_CurrentSession[0], $Crack[2], $Port)
    If @error Then
        _WinHttpCloseHandle($hConnect)
        Return SetError(5, 0, 0)
    EndIf

    Local $hRequest = _WinHttpOpenRequest($hConnect, $Action, $Crack[6] & $Crack[7], Default, $sReferer, Default, $Flag)
    If Not $hRequest Then
        _WinHttpCloseHandle($hConnect)
        Return SetError(6, 0, 0)
    EndIf

    If $Action == "POST" Then
        If ($headers = Default) And ($AdditionalData = Default) Then _WinHttpAddRequestHeaders($hRequest, "Content-Type: application/x-www-form-urlencoded")
    EndIf

    Local $iSize = 0
    If $AdditionalData Then $iSize = StringLen($AdditionalData)

    _WinHttpSetOption($hRequest, $WINHTTP_OPTION_REDIRECT_POLICY, $WINHTTP_OPTION_REDIRECT_POLICY_ALWAYS); allow redirects

    _WinHttpSendRequest($hRequest, $headers, $AdditionalData, $iSize)
    If @error Then
        _WinHttpCloseHandle($hRequest)
        _WinHttpCloseHandle($hConnect)
        Return SetError(7, 0, 0)
    EndIf

    _WinHttpReceiveResponse($hRequest)
    If @error Then
        _WinHttpCloseHandle($hRequest)
        _WinHttpCloseHandle($hConnect)
        Return SetError(8, 0, 0)
    EndIf

    If Not $ReadReturn Then
        _WinHttpCloseHandle($hRequest)
        _WinHttpCloseHandle($hConnect)
        Return SetError(0, 0, 1)
    EndIf

    Local $Data
    If _WinHttpQueryDataAvailable($hRequest) Then
        Local $bChunk
        While 1
            $bChunk = _WinHttpReadData($hRequest, 2)
            If @error Then ExitLoop
            $Data = _WinHttpBinaryConcat($Data, $bChunk)
        WEnd
    Else
        _WinHttpCloseHandle($hRequest)
        _WinHttpCloseHandle($hConnect)
        Return SetError(9, 0, 0)
    EndIf

    Local $aReturn[2] = [$Data, _WinHttpQueryHeaders($hRequest)]

    If StringRegExp($aReturn[1], "(?im)^Content-Type:\h.*?charset\h*=\h*utf-?8") Then $iCharset = 4
    If StringRegExp($aReturn[1], "(?im)^Content-Encoding:\h+gzip") Then
        $Data = _ZLIB_GZUncompress($aReturn[0])
        If $bBinary Then
            $aReturn[0] = Binary($Data)
        Else
            $aReturn[0] = BinaryToString($Data, $iCharset)
        EndIf
    Else
        If $bBinary Then
            $aReturn[0] = Binary($Data)
        Else
            $aReturn[0] = BinaryToString($aReturn[0], $iCharset)
        EndIf
    EndIf

    If $SessionDur = 0 Then _TerminateSession()

    _WinHttpCloseHandle($hRequest)
    _WinHttpCloseHandle($hConnect)
    Return SetError(0, 0, $aReturn)
EndFunc   ;==>_WinHTTP_Action

; #FUNCTION# ====================================================================================================================
; Name ..........: _TerminateSession
; Description ...: Terminates a session after it's idled for a while.
; Syntax ........: _TerminateSession()
; Parameters ....: None
; Return values .: None
; Author ........: ScriptKitty
; Example .......: No
; ===============================================================================================================================
Func _TerminateSession()
    AdlibUnRegister("_TerminateSession")
    If ($_WinHTTP_CurrentSession[0] <> -1) Then
        _WinHttpCloseHandle($_WinHTTP_CurrentSession[0])
        $_WinHTTP_CurrentSession[0] = -1
    EndIf
EndFunc

With the above, I can simply copy/paste quickly into scripts that will do internet things and just deal with the headers, data like form post simulations and stuff like that.

So I'd like to create a similar function in C++ that would let me basically do the same.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...