msdn upload image with winhttp c++ - c++

I have been trying this the whole day but no luck i want to upload an image file to a php file which i have created but when ever i try to do that winhttpsendrequest throws 183 error that means cannot send file that is already sent please can someone point out where i am wrong
c++ code:
int _tmain(int argc, _TCHAR* argv[]) {
HINTERNET hSession = NULL,
hConnect = NULL,
hRequest = NULL;
BOOL bResults = FALSE;
FILE *pFile;
long lSize;
char *buffer;
size_t result;
pFile = fopen("blog.jpg", "rb");
fseek(pFile, 0, SEEK_END);
lSize = ftell(pFile);
rewind(pFile);
buffer = (char *) malloc(sizeof(char) * lSize);
result = fread(buffer, 1, lSize, pFile);
fclose(pFile);
hSession = WinHttpOpen( L"WinHTTP Example/1.0",
WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
WINHTTP_NO_PROXY_NAME,
WINHTTP_NO_PROXY_BYPASS, 0);
if (hSession)
hConnect = WinHttpConnect(hSession, L"localhost",
INTERNET_DEFAULT_HTTP_PORT, 0);
if (hConnect)
hRequest = WinHttpOpenRequest(hConnect, L"POST", L"locker/upload.php",
NULL, WINHTTP_NO_REFERER,
WINHTTP_DEFAULT_ACCEPT_TYPES,
WINHTTP_FLAG_REFRESH);
static WCHAR frmdata[2048] = L"Connection: keep-alive\r\nContent-Type: multipart/form-data; -----------------------------7d82751e2bc0858\r\nContent-Disposition: form-data; name=\"file\"; filename=\"blog.jpg\"\r\nContent-Type: image/jpeg\r\n\r\n";
bResults = WinHttpSendRequest(hRequest,
frmdata, wcslen(frmdata), buffer,
lSize, wcslen(frmdata)+lSize, 0);
if (bResults) {
/*
DWORD dwBytesWritten = 0;
bResults = WinHttpWriteData(hRequest, buffer,
lSize,
&dwBytesWritten);
if (bResults) {
printf_s("Data: %d", dwBytesWritten);
}
*/
} else {
printf_s("SendReq: %d", GetLastError());
}
free(buffer);
if (hRequest) { WinHttpCloseHandle(hRequest); }
if (hConnect) { WinHttpCloseHandle(hConnect); }
if (hSession) { WinHttpCloseHandle(hSession); }
getchar();
return 0;
}
php code:
if (isset($_FILES["file"])) {
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['file']['name']);
if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['file']['name']). " has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
}

Keshav Nair.
try to this code:
CHAR postData[1024];
CHAR postData2[1024];
ZeroMemory(&postData,1024);
ZeroMemory(&postData2,1024);
WinHttpAddRequestHeaders(hRequest,L"Content-Type: multipart/form-data; boundary=----OiRBxC0fjdSEpqhd",-1L,WINHTTP_ADDREQ_FLAG_ADD);
wsprintfA(postData,"%s","----OiRBxC0fjdSEpqhd\r\nContent-Disposition: form-data; name=\"file\"; filename=\"blog.jpg\"\r\nContent-Type: image/jpeg\r\n\r\n");
wsprintfA(postData2,"%s","\r\n----OiRBxC0fjdSEpqhd\r\nContent-Disposition: form-data; name=\"submit\"\r\n\r\nSubmit\r\n----OiRBxC0fjdSEpqhd--\r\n");
bResults = WinHttpSendRequest( hRequest,
WINHTTP_NO_ADDITIONAL_HEADERS,
0, WINHTTP_NO_REQUEST_DATA, 0,
lstrlenA(postData)+lstrlenA(postData2)+lSize, NULL);
if (bResults)
{
bResults=WinHttpWriteData(hRequest,LPCVOID)postData,lstrlenA(postData),NULL);
bResults = WinHttpWriteData(hRequest, buffer, lSize, &dwBytesWritten);
bResults=WinHttpWriteData(hRequest,(LPCVOID)postData2,lstrlenA(postData2),NULL);
}
WinHttpWriteData:
POST data - postData, postData2 must be 8 bit encoding.

Related

Getting encrypted body response WinHttp HTTPS

I'm trying to connect with google.com with port 443 SSL but when i call to WinHttpReadData returns encrypted text, but with WinHttpQueryHeaders i'm getting plain/text response headers from server.
Not sure at all why happens that, im referring to Headers no encrypted and Body yes, my objective is get the response body decrypted.
The source is here:
// ConsoleApplication3.cpp : Este archivo contiene la función "main". La ejecución del programa comienza y termina ahí.
//
#include "pch.h"
#include <windows.h>
#include <winhttp.h>
#include <iostream>
#include <string>
#include <algorithm>
int main(){
DWORD dwSize = 2000;
DWORD dwDownloaded = 0;
LPSTR pszOutBuffer;
DWORD headerSize = 0;
char * lpOutBuffer = new char[dwSize / sizeof(char)];
HINTERNET hSession = NULL;
HINTERNET hConnect = NULL;
HINTERNET hRequest = NULL;
// Use WinHttpOpen to obtain a session handle.
hSession = WinHttpOpen(L"WinHTTP Example/1.0",
WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
WINHTTP_NO_PROXY_NAME,
WINHTTP_NO_PROXY_BYPASS, 0);
// Specify an HTTP server.
if (hSession)
hConnect = WinHttpConnect(hSession, L"google.com",
443, 0); //443 port for SSL/TLS
std::cout << "hConnect " << hConnect << std::endl;
// Create an HTTP request handle.
if (hConnect)
hRequest = WinHttpOpenRequest(hConnect, L"GET", L"/",
L"HTTP/1.1", WINHTTP_NO_REFERER,
NULL,
WINHTTP_FLAG_SECURE); //SECURE FLAG
std::cout << "hRequest " << hRequest << std::endl;
if (hRequest) { //Adding Headers
std::cout << "Añadiendo headers!\n";
WinHttpAddRequestHeaders(hRequest,
L"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
-1L,
WINHTTP_ADDREQ_FLAG_ADD);
WinHttpAddRequestHeaders(hRequest,
L"Accept-Encoding: gzip, deflate, br",
-1L,
WINHTTP_ADDREQ_FLAG_ADD);
WinHttpAddRequestHeaders(hRequest,
L"Accept-Language: es-ES,es;q=0.8,en-US;q=0.5,en;q=0.3",
-1L,
WINHTTP_ADDREQ_FLAG_ADD);
WinHttpAddRequestHeaders(hRequest,
L"Connection: keep-alive",
-1L,
WINHTTP_ADDREQ_FLAG_ADD);
WinHttpAddRequestHeaders(hRequest,
L"Host: google.com",
-1L,
WINHTTP_ADDREQ_FLAG_ADD);
WinHttpAddRequestHeaders(hRequest,
L"Upgrade-Insecure-Requests: 1",
-1L,
WINHTTP_ADDREQ_FLAG_ADD);
WinHttpAddRequestHeaders(hRequest,
L"User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:76.0) Gecko/20100101 Firefox/76.0",
-1L,
WINHTTP_ADDREQ_FLAG_ADD);
}
// Send a request.
BOOL bResults;
if (hRequest)
bResults = WinHttpSendRequest(hRequest,
WINHTTP_NO_ADDITIONAL_HEADERS,
0, WINHTTP_NO_REQUEST_DATA, 0,
0, 0);
std::cout << "bResults " << bResults << " " << GetLastError() << std::endl;
if (bResults)
bResults = WinHttpReceiveResponse(hRequest, NULL);
std::cout << "bResults " << bResults << " " << GetLastError() << std::endl;
if (bResults)
{
WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_RAW_HEADERS,
WINHTTP_HEADER_NAME_BY_INDEX, NULL,
&dwSize, WINHTTP_NO_HEADER_INDEX);
printf("Tamaño de los headers: %d", dwSize);
// Allocate memory for the buffer.
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
{
lpOutBuffer = new char[dwSize / sizeof(char)];
// Now, use WinHttpQueryHeaders to retrieve the header.
bResults = WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_RAW_HEADERS,
WINHTTP_HEADER_NAME_BY_INDEX,
lpOutBuffer, &dwSize,
WINHTTP_NO_HEADER_INDEX);
if (bResults){
char * headers_aqui = new char[dwSize / sizeof(char)];
int dwSize2 = 0;
for (int i = 0,i2 = 0; i < dwSize; i++) {
//std::cout << (int)str[i] << std::endl;
if ((int)lpOutBuffer[i] != 0) {
headers_aqui[i2] = lpOutBuffer[i];
dwSize2 = i2;
i2++;
}
}
std::cout << "Tamaño ahora: " << dwSize2 << std::endl;
std::string str(headers_aqui, dwSize2);
std::cout << "Header contents: \n" << str << "\n\n\n\n\n"; //No encrypted or compressed.
}
}
}
if (bResults)
{
do
{
// Check for available data.
dwSize = 0;
if (!WinHttpQueryDataAvailable(hRequest, &dwSize))
printf("Error %u in WinHttpQueryDataAvailable.\n",
GetLastError());
// Allocate space for the buffer.
pszOutBuffer = new char[dwSize + 1];
if (!pszOutBuffer)
{
printf("Out of memory\n");
dwSize = 0;
}
else
{
// Read the data.
ZeroMemory(pszOutBuffer, dwSize + 1);
if (!WinHttpReadData(hRequest, (LPVOID)pszOutBuffer,
dwSize, &dwDownloaded))
printf("Error %u in WinHttpReadData.\n", GetLastError());
else
printf("%s", pszOutBuffer); //Encrypted or compressed, think SSL encryption.
// Free the memory allocated to the buffer.
delete[] pszOutBuffer;
}
} while (dwSize > 0);
}
// Report any errors.
if (!bResults)
printf("Error %d has occurred.\n", GetLastError());
// Close any open handles.
if (hRequest) WinHttpCloseHandle(hRequest);
if (hConnect) WinHttpCloseHandle(hConnect);
if (hSession) WinHttpCloseHandle(hSession);
//std::cout << "Hello World!\n";
}
Output here: https://pastebin.com/cSkEugDT
I read the documentation but don't find anything about decryption of content in WinHttpReadData, obviously this happens only with https, when i test http it's return plain/text.
I suspect about some parameter to before calls to WinHttpReadData.
Finally i get the mistake, this was on header Accept-Encoding
WinHttpAddRequestHeaders(hRequest,
L"Accept-Encoding: gzip, deflate, br",
-1L,
WINHTTP_ADDREQ_FLAG_ADD);
I commented and fix the issue. GZIP is a compression algorithm whos made this compressed text (deflate and br another algorithms with same purpose).
About Accept-Encoding header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding

HTTP POST request via Wininet

In VC++, I am trying to send an HTTP POST request and get its response.
I have the below code, which compiles successfully, yet fails to POST.
First I try to send the POST request to the request bin for testing purpose
int main(int argc, _TCHAR* argv[])
{
static CHAR hdrs[] = "Content-Type: application/x-www-form-urlencoded";
static CHAR frmdata[] = "name=John+Doe&userid=hithere&other=P%26Q";
HINTERNET hSession = InternetOpenA("MyAgent", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
HINTERNET hConnect = InternetConnect(hSession "pipedream.com", 8733, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 1);
HINTERNET hRequest = HttpOpenRequestA(hConnect, "POST", "/r/enj77inn26shk", NULL, NULL, NULL, 0, 1);
HttpSendRequestA(hRequest, hdrs, strlen(hdrs), frmdata, strlen(frmdata));
Then read the response using
DWORD dwContentLen;
DWORD dwBufLen = sizeof(dwContentLen);
if (HttpQueryInfo(hRequest,
HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER,
(LPVOID)&dwContentLen,
&dwBufLen,
0))
{
char *pData = (char*)GlobalAlloc(GMEM_FIXED, dwContentLen + 1);
DWORD dwReadSize = dwContentLen / 10; // We will read 10% of data
// with each read.
DWORD cReadCount;
DWORD dwBytesRead;
char *pCopyPtr = pData;
for (cReadCount = 0; cReadCount < 10; cReadCount++)
{
InternetReadFile(hRequest, pCopyPtr, dwReadSize, &dwBytesRead);
pCopyPtr = pCopyPtr + dwBytesRead;
}
// extra read to account for integer division round off
InternetReadFile(hRequest,
pCopyPtr,
dwContentLen - (pCopyPtr - pData),
&dwBytesRead);
// Null terminate data
pData[dwContentLen] = 0;
std::cout << pData << std::endl;
system("pause");
}
return 0;
}
The endpoint I'm posting to

send multipart/form-data using httpsendrequest

I'm trying to send multipart/form-data using httpsendrequest in c++ but it doesn't seem to work. I'm using the RFC standard for boundary and this is the code I have. I'm sending simple data, plain but trying to use multipart/form-data so I can understand how boundaries work but it doesn't send. This is the code that I've got so far.
#define _WIN32_WINNT 0x600
#include <stdio.h>
#include <wininet.h>
#define BUFLEN 1024
static LPCTSTR acceptTypes[] = {"*/*", NULL};
static const char *postData = "submit=submit&cool=hawk";
static char headers[] = TEXT("Content-Type: multipart/form-data; boundary=abcde\r\n"
"--abcde\r\n"
"Content-Disposition: form-data; name=\"cool\"\r\n"
"testval\r\n"
"--abcde\r\n");
int main()
{
HINTERNET hSession, hConnect, hFile;
if( ( hSession = InternetOpen(
"myapp",
INTERNET_OPEN_TYPE_PRECONFIG,
NULL,
NULL,
0
) ) == NULL )
{
printf("Couldn't start session. Error %ld\n", GetLastError());
exit(1);
}
printf("Session started\n");
if( ( hConnect = InternetConnect(
hSession,
"localhost",
INTERNET_DEFAULT_HTTP_PORT,
NULL,
NULL,
INTERNET_SERVICE_HTTP,
0,
0
) ) == NULL )
{
printf("Unable to connect to server. Error %ld\n", GetLastError());
exit(1);
}
printf("Connected to server\n");
if( ( hFile = HttpOpenRequest(
hConnect,
"POST",
"/test/index.php",
NULL,
NULL,
acceptTypes,
INTERNET_FLAG_RELOAD,
0
) ) == NULL )
{
printf("Unable to open request. Error %ld\n", GetLastError());
exit(1);
}
printf("Opening request..Opened\n");
unsigned long dataLen = strlen(postData)+1;
bool res = HttpSendRequest(
hFile,
headers,
-1,
(char*)postData,
dataLen
);
if( !res )
{
printf("Unable to send request. Error %ld\n", GetLastError());
exit(1);
}
printf("Request sent\n");
// char *szBuffer = (char*)malloc(sizeof(char)*BUFLEN);
char szBuffer[BUFLEN];
DWORD dwRead = 0;
memset(&szBuffer, '\0', sizeof(szBuffer));
while( InternetReadFile(hFile, szBuffer, sizeof(szBuffer), &dwRead) && dwRead )
{
printf("%s", szBuffer);
}
return 0;
}

C++ WinHttp get response header and body

I'm currently trying to write a class to make sending simple requests easier for me.
In the end I'd like it to be usable somewhat like this:
int _tmain(int argc, _TCHAR* argv[])
{
HttpRequest Request(L"Example UserAgent/1.0",L"",L"");
Request.SendRequest(L"google.com",L"GET",NULL);
if (Request.responseHeader)
printf("%s",Request.responseHeader);
if (Request.responseBody)
printf("%s",Request.responseBody);
getchar();
return 0;
}
But for now it doesn't work at all. I have no idea how I could get the response header and I'm failing writing the response header to a public member of my class.
Yeah I'm really bad at C++ especially when it's about the winapi.
Well I hope you can help me out.
Here is my code so far:
#include "stdafx.h"
#include <windows.h>
#include <winhttp.h>
#pragma comment(lib, "winhttp.lib")
class HttpRequest {
private:
DWORD dwSize;
DWORD dwDownloaded;
LPSTR pszOutBuffer;
BOOL bResults;
HINTERNET hSession;
HINTERNET hConnect;
HINTERNET hRequest;
LPCWSTR _userAgent;
//LPCWSTR _proxyIp;
//LPCWSTR _proxyPort;
size_t bodySize;
public:
HttpRequest(LPCWSTR, LPCWSTR, LPCWSTR);
void SendRequest(LPCWSTR, LPCWSTR, LPVOID);
LPSTR responseHeader[1000000];
LPSTR responseBody[1000000];
};
HttpRequest::HttpRequest(LPCWSTR userAgent, LPCWSTR proxyIp, LPCWSTR proxyPort) {
_userAgent = userAgent;
//_proxyIp = proxyIp;
//_proxyPort = proxyPort;
hSession = WinHttpOpen( userAgent, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0 );
}
void HttpRequest::SendRequest(LPCWSTR url, LPCWSTR method, LPVOID body) {
bodySize = 0;
if (hSession)
hConnect = WinHttpConnect( hSession, url, INTERNET_DEFAULT_HTTPS_PORT, 0 );
else
printf("session handle failed\n");
if (hConnect)
hRequest = WinHttpOpenRequest( hConnect, method, NULL, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE );
else
printf("connect handle failed\n");
if (hRequest)
bResults = WinHttpSendRequest( hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, body, 0, 0, 0 );
else
printf("request handle failed\n");
if( bResults )
bResults = WinHttpReceiveResponse( hRequest, NULL );
if( bResults )
{
do
{
// Check for available data.
dwSize = 0;
if( !WinHttpQueryDataAvailable( hRequest, &dwSize ) )
printf( "Error %u in WinHttpQueryDataAvailable.\n", GetLastError( ) );
// Allocate space for the buffer.
pszOutBuffer = new char[dwSize+1];
if( !pszOutBuffer )
{
printf( "Out of memory\n" );
dwSize=0;
}
else
{
// Read the data.
ZeroMemory( pszOutBuffer, dwSize+1 );
if( !WinHttpReadData( hRequest, (LPVOID)pszOutBuffer, dwSize, &dwDownloaded ) )
printf( "Error %u in WinHttpReadData.\n", GetLastError( ) );
else {
//printf( "%s", pszOutBuffer );
responseBody[bodySize++] = pszOutBuffer;
}
// Free the memory allocated to the buffer.
delete [] pszOutBuffer;
}
} while( dwSize > 0 );
}
// Report any errors.
if( !bResults )
printf( "Error %d has occurred.\n", GetLastError( ) );
// Close any open handles.
if( hRequest ) WinHttpCloseHandle( hRequest );
if( hConnect ) WinHttpCloseHandle( hConnect );
if( hSession ) WinHttpCloseHandle( hSession );
}
Use WinHttpQueryHeaders() to access the response headers. Use the WINHTTP_QUERY_RAW_HEADERS(_CRLF) flag to specify that you want to retrieve all of the available headers.
You also need to change your class to dynamically allocate its responseHeader and responseBody members. You are wasting a lot of memory, as well as limiting the response size you can handle, by using static arrays.
Try this:
#include "stdafx.h"
#include <windows.h>
#include <winhttp.h>
#include <string>
#include <vector>
#pragma comment(lib, "winhttp.lib")
class HttpRequest
{
private:
std::wstring _userAgent;
//std::wstring _proxyIp;
//std::wstring _proxyPort;
public:
HttpRequest(const std::wstring&, const std::wstring&, const std::wstring&);
bool SendRequest(const std::wstring&, const std::wstring&, void*, DWORD);
std::wstring responseHeader;
std::vector<BYTE> responseBody;
};
HttpRequest::HttpRequest(const std::wstring &userAgent, const std::wstring &proxyIp, const std::wstring &proxyPort) :
_userAgent(userAgent)
//,_proxyIp(proxyIp)
//,_proxyPort(proxyPort)
{
}
bool HttpRequest::SendRequest(const std::wstring &url, const std::wstring &method, void *body, DWORD bodySize)
{
DWORD dwSize;
DWORD dwDownloaded;
DWORD headerSize = 0;
BOOL bResults = FALSE;
HINTERNET hSession;
HINTERNET hConnect;
HINTERNET hRequest;
responseHeader.resize(0);
responseBody.resize(0);
hSession = WinHttpOpen( _userAgent.c_str(), WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0 );
if (hSession)
hConnect = WinHttpConnect( hSession, url.c_str(), INTERNET_DEFAULT_HTTPS_PORT, 0 );
else
printf("session handle failed\n");
if (hConnect)
hRequest = WinHttpOpenRequest( hConnect, method.c_str(), NULL, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE );
else
printf("connect handle failed\n");
if (hRequest)
bResults = WinHttpSendRequest( hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, body, bodySize, 0, 0 );
else
printf("request handle failed\n");
if (bResults)
bResults = WinHttpReceiveResponse( hRequest, NULL );
if (bResults)
{
bResults = WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_RAW_HEADERS_CRLF, NULL, WINHTTP_NO_OUTPUT_BUFFER, &headerSize, WINHTTP_NO_HEADER_INDEX);
if ((!bResults) && (GetLastError() == ERROR_INSUFFICIENT_BUFFER))
{
responseHeader.resize(headerSize / sizeof(wchar_t));
if (responseHeader.empty())
{
bResults = TRUE;
}
else
{
bResults = WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_RAW_HEADERS_CRLF, NULL, &responseHeader[0], &headerSize, WINHTTP_NO_HEADER_INDEX);
if( !bResults ) headerSize = 0;
responseHeader.resize(headerSize / sizeof(wchar_t));
}
}
}
if (bResults)
{
do
{
// Check for available data.
dwSize = 0;
bResults = WinHttpQueryDataAvailable( hRequest, &dwSize );
if (!bResults)
{
printf( "Error %u in WinHttpQueryDataAvailable.\n", GetLastError( ) );
break;
}
if (dwSize == 0)
break;
do
{
// Allocate space for the buffer.
DWORD dwOffset = responseBody.size();
responseBody.resize(dwOffset+dwSize);
// Read the data.
bResults = WinHttpReadData( hRequest, &responseBody[dwOffset], dwSize, &dwDownloaded );
if (!bResults)
{
printf( "Error %u in WinHttpReadData.\n", GetLastError( ) );
dwDownloaded = 0;
}
responseBody.resize(dwOffset+dwDownloaded);
if (dwDownloaded == 0)
break;
dwSize -= dwDownloaded;
}
while (dwSize > 0);
}
while (true);
}
// Report any errors.
if (!bResults)
printf( "Error %d has occurred.\n", GetLastError( ) );
// Close any open handles.
if( hRequest ) WinHttpCloseHandle( hRequest );
if( hConnect ) WinHttpCloseHandle( hConnect );
if( hSession ) WinHttpCloseHandle( hSession );
return bResults;
}
int _tmain(int argc, _TCHAR* argv[])
{
HttpRequest Request(L"Example UserAgent/1.0",L"",L"");
if (Request.SendRequest(L"google.com",L"GET",NULL,0))
{
printf("%ls",Request.responseHeader.c_str());
if (!Request.responseBody.empty())
printf("%*s",Request.responseBody.size(),(char*)&Request.responseBody[0]);
}
getchar();
return 0;
}

C++ NPAPI WinHttpConnect failed

Now i know the problem is hConnect not successfully initialize through the debugger, and i wonder why,thanks
its the javascript code caller
t=function(){
var type = "GET",
host = "183.60.139.201",
port = 80,
uri = "/",
useragent = "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US)",
headers = "";
getdata = "",
postdata = "";
resolveTimeout = 10000;
connectTimeout = 10000;
sendTimeout = 10000;
receiveTimeout = 10000;
return test.http( type
,host
,port
,uri
,useragent
,headers
,getdata
,postdata
,resolveTimeout
,connectTimeout
,sendTimeout
,receiveTimeout
);
}
t();
its C++ source
#include "plugin.h"
#include "simplehttp.h"
#pragma comment(lib, "winhttp.lib")
#include <windows.h>
#include <winhttp.h>
#include <string>
std::wstring s2ws(const std::string& s)
{
int len;
int slength = (int)s.length() + 1;
len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0);
wchar_t* buf = new wchar_t[len];
MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);
std::wstring r(buf);
delete[] buf;
return r;
}
using namespace std;
bool HttpRequest(ScriptablePluginObject* obj, const NPVariant* args,
unsigned int argCount, NPVariant* result){
string type = "GET";
string host = "";
unsigned int port = INTERNET_DEFAULT_HTTP_PORT;
string uri ="/";
string useragent = "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US)";
string additionalheaders = "";
string getdata = "";
string postdata = "";
__asm {
int 3
}
unsigned int resolveTimeout = 10000;
unsigned int connectTimeout = 10000;
unsigned int sendTimeout = 10000;
unsigned int receiveTimeout = 10000;
for( int i=0;i<argCount;i++){
NPVariant arg = args[i];
switch (i){
case 0:
type = arg.value.stringValue.UTF8Characters;
break;
case 1:
host = arg.value.stringValue.UTF8Characters;
break;
case 2:
port = arg.value.intValue;
break;
case 3:
uri = arg.value.stringValue.UTF8Characters;
break;
case 4:
useragent = arg.value.stringValue.UTF8Characters;
break;
case 5:
additionalheaders = arg.value.stringValue.UTF8Characters;
break;
case 6:
getdata = arg.value.stringValue.UTF8Characters;
break;
case 7:
postdata = arg.value.stringValue.UTF8Characters;
break;
case 8:
resolveTimeout = arg.value.intValue;
break;
case 9:
connectTimeout = arg.value.intValue;
break;
case 10:
sendTimeout = arg.value.intValue;
break;
case 11:
receiveTimeout = arg.value.intValue;
break;
}
}
BOOL usePost = (type == "POST" && postdata != "");
DWORD dwSize = 0;
DWORD dwDownloaded = 0;
LPSTR pszOutBuffer;
BOOL bResults = FALSE;
string page = "";
HINTERNET hSession = NULL,
hConnect = NULL,
hRequest = NULL;
hSession = WinHttpOpen( s2ws(useragent).c_str(),
WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
WINHTTP_NO_PROXY_NAME,
WINHTTP_NO_PROXY_BYPASS,
0);
if (!WinHttpSetTimeouts( hSession, resolveTimeout, connectTimeout, sendTimeout, receiveTimeout)){
goto endHttpRequest;
};
if(hSession){
LPCWSTR tes = s2ws(host).c_str();
hConnect = WinHttpConnect( hSession,
tes,
port,
0);
}else{
goto endHttpRequest;
}
if(hConnect){ // FAILED HERE!!!!
if(!usePost){
hRequest = WinHttpOpenRequest( hConnect,
s2ws(type).c_str(),
s2ws(uri.append(getdata)).c_str(),
NULL,
WINHTTP_NO_REFERER,
WINHTTP_DEFAULT_ACCEPT_TYPES,
WINHTTP_FLAG_REFRESH);
}else{
hRequest = WinHttpOpenRequest( hConnect,
s2ws(type).c_str(),
s2ws(uri).c_str(),
NULL,
WINHTTP_NO_REFERER,
WINHTTP_DEFAULT_ACCEPT_TYPES,
WINHTTP_FLAG_REFRESH);
}
}else{
goto endHttpRequest;
}
if(hRequest)
bResults = WinHttpAddRequestHeaders( hRequest,
L"Cookie:",
-1,
WINHTTP_ADDREQ_FLAG_REPLACE);
if(hRequest)
bResults = WinHttpAddRequestHeaders( hRequest,
s2ws(additionalheaders).c_str(),
-1,
WINHTTP_ADDREQ_FLAG_ADD);
if(hRequest)
{
if(usePost){
bResults = WinHttpAddRequestHeaders( hRequest,
L"Content-Type: application/x-www-form-urlencoded",
-1,
WINHTTP_ADDREQ_FLAG_ADD);
bResults = WinHttpAddRequestHeaders( hRequest,
L"Content-Length: "+ postdata.size(),
-1,
WINHTTP_ADDREQ_FLAG_ADD);
bResults = WinHttpSendRequest( hRequest,
WINHTTP_NO_ADDITIONAL_HEADERS,
0,
(LPVOID)postdata.c_str(),
postdata.size(),
postdata.size(),
0);
}else{
bResults = WinHttpSendRequest( hRequest,
WINHTTP_NO_ADDITIONAL_HEADERS,
0,
WINHTTP_NO_REQUEST_DATA,
0,
0,
0);
}
}
if(bResults){
bResults = WinHttpReceiveResponse(hRequest,NULL);
}else{
goto endHttpRequest;
}
if(bResults){
do{
dwSize = 0;
if(!WinHttpQueryDataAvailable( hRequest,&dwSize)){
return false;
}
pszOutBuffer = new char[dwSize+1];
if(!pszOutBuffer){
dwSize = 0;
return false;
}else{
ZeroMemory(pszOutBuffer,dwSize+1);
if(!WinHttpReadData( hRequest,
(LPVOID)pszOutBuffer,
dwSize,
&dwDownloaded)){
return false;
}else{
page.append(pszOutBuffer);
}
delete [] pszOutBuffer;
}
}while(dwSize>0);
}
endHttpRequest:
char* npOutString = (char *)npnfuncs->memalloc(page.size()+1);
strcpy(npOutString,page.c_str());
STRINGZ_TO_NPVARIANT(npOutString,*result);
if( hRequest ) WinHttpCloseHandle( hRequest );
if( hConnect ) WinHttpCloseHandle( hConnect );
if( hSession ) WinHttpCloseHandle( hSession );
return true;
};
I've seen this error in python, the solution was to pass the url string in utf-16 encoding.
try using wstring uri;
The wide version then you don't need to convert it.