BOOL HttpRequest(HTTPREQ* req, const wchar_t* url, const wchar_t* header, DWORD header_length, const char* body, DWORD body_length) { BOOL ret = FALSE; req->internet = WinHttpOpen(NULL, NULL, NULL, NULL, NULL); if (req->internet != NULL) { URL_COMPONENTS urlinfo = {0}; urlinfo.dwStructSize = sizeof(URL_COMPONENTS); urlinfo.dwSchemeLength = (DWORD)-1; urlinfo.dwUserNameLength = (DWORD)-1; urlinfo.dwHostNameLength = (DWORD)-1; urlinfo.dwUrlPathLength = (DWORD)-1; urlinfo.dwExtraInfoLength = (DWORD)-1; urlinfo.dwPasswordLength = (DWORD)-1; if (WinHttpCrackUrl(url, wcslen(url), 0, &urlinfo)) { if (WinHttpSetTimeouts(req->internet, req->resolveTimeout, req->connectTimeout, req->sendTimeout, req->receiveTimeout)) { TCHAR* host = new TCHAR[urlinfo.dwHostNameLength + 1]; wmemset(host, 0, urlinfo.dwHostNameLength + 1); StrCpyN(host, urlinfo.lpszHostName, urlinfo.dwHostNameLength + 1); req->connect = WinHttpConnect(req->internet, host, urlinfo.nPort, 0); if (req->connect != NULL) { if (body == NULL || body_length == 0) req->request = WinHttpOpenRequest(req->connect, L"GET", urlinfo.lpszUrlPath, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0); else req->request = WinHttpOpenRequest(req->connect, L"POST", urlinfo.lpszUrlPath, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0); if (req->request != NULL) { if (WinHttpSendRequest(req->request, header, header_length, (void*)body, body_length, body_length, 0) && WinHttpReceiveResponse(req->request, 0)) { TCHAR status[16] = {0}; DWORD size = sizeof(status); if (WinHttpQueryHeaders(req->request, WINHTTP_QUERY_STATUS_CODE, NULL, status, &size, 0)) { if (StrCmp(status, L"200") == 0) { char buffer[4096] = {0}; DWORD length = 0; while (TRUE) { if (WinHttpReadData(req->request, buffer, sizeof(buffer), &length) && length > 0) { AppendBuffer(&req->buffer, req->dataLength, req->bufferLength, buffer, length); length = 0; } else break; } ret = TRUE; } } } } } SAFE_DELETE_ARRAY(host); } } } return ret; }
//------------------------------------------------------------------------------------------------------------------------ const char *CHttpClient::SendRequest(const wchar_t * verb, const wchar_t * target_url, const wchar_t * headers, const wchar_t * body) { CParsedURL<wchar_t> url; url.Parse(target_url); HINTERNET hConnect = NULL, hRequest = NULL; if (hSession) // Specify an HTTP server. hConnect = WinHttpConnect(hSession, url.Base(), url.is_https ? INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT, 0); if (hConnect) // Create an HTTP request handle. hRequest = WinHttpOpenRequest(hConnect, verb, url.Route(), NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0); BOOL bResults = FALSE; if (hRequest) // Send a request. { if (body==nullptr) // indicates a GET request bResults = WinHttpSendRequest(hRequest, headers, wcslen(headers), WINHTTP_NO_REQUEST_DATA, 0, 0, NULL); else bResults = WinHttpSendRequest(hRequest, headers, wcslen(headers), (LPVOID)body, (DWORD)wcslen(body) * 2, (DWORD)wcslen(body) * 2, NULL); } if (bResults)// End the request. bResults = WinHttpReceiveResponse(hRequest, NULL); response.clear(); // Keep checking for data until there is nothing left. if (bResults) for (DWORD dwSize = 1; dwSize > 0;) { if (!WinHttpQueryDataAvailable(hRequest, &dwSize)) // Check for available data. StoreErrorCode(); LPSTR pszOutBuffer = new char[dwSize + 1]; // Allocate space for the buffer. if (!pszOutBuffer) { //ReportError("Out of memory\n", -1); dwSize = 0; } else { ZeroMemory(pszOutBuffer, dwSize + 1); DWORD dwDownloaded = 0; if (WinHttpReadData(hRequest, (LPVOID)pszOutBuffer, dwSize, &dwDownloaded)) // Read the data. response.append(pszOutBuffer); else StoreErrorCode(); delete[] pszOutBuffer;// Free the memory allocated to the buffer. } } else // !bResults StoreErrorCode(); // Close any open handles. if (hRequest) WinHttpCloseHandle(hRequest); if (hConnect) WinHttpCloseHandle(hConnect); return last_err_code? nullptr : response.c_str(); }
bool uploadToImgur(Image* image, String& response) { MemWriteFile memRaw; image->writePNG(&memRaw); bool success = false; response = "Failed to connect"; HINTERNET hSession = WinHttpOpen(L"MuleView", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, NULL, NULL, 0); if (hSession) { HINTERNET hConnect = WinHttpConnect(hSession, L"api.imgur.com", INTERNET_DEFAULT_HTTPS_PORT, 0); if (hConnect) { HINTERNET hRequest = WinHttpOpenRequest(hConnect, L"POST", L"/3/image", L"HTTP/1.1", WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE); if (hRequest) { wchar_t* headers = L"Authorization: Client-ID b7668fe01959177\r\n" L"Content-Type: image/png\r\n"; BOOL result = WinHttpSendRequest(hRequest, headers, -1, memRaw.buffer(), memRaw.size(), memRaw.size(), NULL); if (result) result = WinHttpReceiveResponse(hRequest, NULL); DWORD avail; if (result) result = WinHttpQueryDataAvailable(hRequest, &avail); if (result) { char* ptr = new char[avail + 1]; WinHttpReadData(hRequest, ptr, avail, &avail); ptr[avail] = 0; LocalPtr<json::Value> value = json::Value::parse(File::memfile(ptr, avail, false)); json::Value* sub = (value && value->type() == json::Value::tObject ? value->get("data") : NULL); json::Value* sub2 = (sub && sub->type() == json::Value::tObject ? sub->get("id") : NULL); if (sub2 && sub2->type() == json::Value::tString) { success = true; response = sub2->getString(); } else { sub2 = (sub && sub->type() == json::Value::tObject ? sub->get("error") : NULL); if (sub2 && sub2->type() == json::Value::tString) response = sub2->getString(); } delete[] ptr; } WinHttpCloseHandle(hRequest); } WinHttpCloseHandle(hConnect); } WinHttpCloseHandle(hSession); } return success; }
// POST request to URL void WinHttpIO::post(HttpReq* req, const char* data, unsigned len) { LOG_debug << "POST target URL: " << req->posturl << " chunked: " << req->chunked; if (req->binary) { LOG_debug << "[sending " << (data ? len : req->out->size()) << " bytes of raw data]"; } else { LOG_debug << "Sending: " << *req->out; } WinHttpContext* httpctx; WCHAR szURL[8192]; WCHAR szHost[256]; URL_COMPONENTS urlComp = { sizeof urlComp }; urlComp.lpszHostName = szHost; urlComp.dwHostNameLength = sizeof szHost / sizeof *szHost; urlComp.dwUrlPathLength = (DWORD)-1; urlComp.dwSchemeLength = (DWORD)-1; httpctx = new WinHttpContext; httpctx->httpio = this; httpctx->req = req; httpctx->gzip = false; req->httpiohandle = (void*)httpctx; if (MultiByteToWideChar(CP_UTF8, 0, req->posturl.c_str(), -1, szURL, sizeof szURL / sizeof *szURL) && WinHttpCrackUrl(szURL, 0, 0, &urlComp)) { if ((httpctx->hConnect = WinHttpConnect(hSession, szHost, urlComp.nPort, 0))) { httpctx->hRequest = WinHttpOpenRequest(httpctx->hConnect, L"POST", urlComp.lpszUrlPath, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, (urlComp.nScheme == INTERNET_SCHEME_HTTPS) ? WINHTTP_FLAG_SECURE : 0); if (httpctx->hRequest) { if (proxyUsername.size()) { LOG_verbose << "Setting proxy credentials"; WinHttpSetCredentials(httpctx->hRequest, WINHTTP_AUTH_TARGET_PROXY, WINHTTP_AUTH_SCHEME_BASIC, (LPWSTR)proxyUsername.data(), (LPWSTR)proxyPassword.data(), NULL); } WinHttpSetTimeouts(httpctx->hRequest, 58000, 58000, 0, 0); WinHttpSetStatusCallback(httpctx->hRequest, asynccallback, WINHTTP_CALLBACK_FLAG_DATA_AVAILABLE | WINHTTP_CALLBACK_FLAG_READ_COMPLETE | WINHTTP_CALLBACK_FLAG_HEADERS_AVAILABLE | WINHTTP_CALLBACK_FLAG_REQUEST_ERROR | WINHTTP_CALLBACK_FLAG_SECURE_FAILURE | WINHTTP_CALLBACK_FLAG_SENDREQUEST_COMPLETE | WINHTTP_CALLBACK_FLAG_SEND_REQUEST | WINHTTP_CALLBACK_FLAG_WRITE_COMPLETE | WINHTTP_CALLBACK_FLAG_HANDLES, 0); LPCWSTR pwszHeaders = req->type == REQ_JSON || !req->buf ? L"Content-Type: application/json\r\nAccept-Encoding: gzip" : L"Content-Type: application/octet-stream"; // data is sent in HTTP_POST_CHUNK_SIZE instalments to ensure // semi-smooth UI progress info if (req->chunkedout.size()) { req->outbuf.append(req->chunkedout); req->chunkedout.clear(); } req->chunked = 0; httpctx->postlen = data ? len : req->out->size(); httpctx->postdata = data ? data : req->out->data(); if (urlComp.nPort == 80) { LOG_verbose << "HTTP connection"; // HTTP connection: send a chunk of data immediately httpctx->postpos = (httpctx->postlen < HTTP_POST_CHUNK_SIZE) ? httpctx->postlen : HTTP_POST_CHUNK_SIZE; } else { LOG_verbose << "HTTPS connection"; // HTTPS connection: ignore certificate errors, send no data yet DWORD flags = SECURITY_FLAG_IGNORE_CERT_CN_INVALID | SECURITY_FLAG_IGNORE_CERT_DATE_INVALID | SECURITY_FLAG_IGNORE_UNKNOWN_CA; WinHttpSetOption(httpctx->hRequest, WINHTTP_OPTION_SECURITY_FLAGS, &flags, sizeof flags); httpctx->postpos = 0; } if (WinHttpSendRequest(httpctx->hRequest, pwszHeaders, wcslen(pwszHeaders), (LPVOID)httpctx->postdata, httpctx->postpos, httpctx->postlen, (DWORD_PTR)httpctx)) { LOG_verbose << "Request sent"; req->status = REQ_INFLIGHT; return; } LOG_err << "Error sending request: " << req->posturl << " Code: " << GetLastError(); } else { LOG_err << "Error opening request: " << req->posturl << " Code: " << GetLastError(); } } else { LOG_err << "Error connecting to " << req->posturl << " Code: " << GetLastError(); httpctx->hRequest = NULL; } } else { LOG_err << "Error parsing POST URL: " << req->posturl << " Code: " << GetLastError(); httpctx->hRequest = NULL; httpctx->hConnect = NULL; } LOG_err << "Request failed"; req->status = REQ_FAILURE; }
/*! * @brief Wrapper around WinHTTP-specific sending functionality. * @param ctx Pointer to the current HTTP transport context. * @param hReq HTTP request handle. * @param buffer Pointer to the buffer to receive the data. * @param size Buffer size. * @return An indication of the result of sending the request. */ static BOOL send_request_winhttp(HttpTransportContext* ctx, HANDLE hReq, LPVOID buffer, DWORD size) { if (ctx->custom_headers) { dprintf("[WINHTTP] Sending with custom headers: %S", ctx->custom_headers); return WinHttpSendRequest(hReq, ctx->custom_headers, -1L, buffer, size, size, 0); } return WinHttpSendRequest(hReq, NULL, 0, buffer, size, size, 0); }
bool CWinHttp::SendRequest(PVOID pBuffer,int LenOfData) { bool bRet=false, bResults=false; //int n=GetLastError(); if(!hRequest) goto exit0; // Send a request. if(lstrcmpW(m_strVerb,L"GET")==0) { bResults = WinHttpSendRequest( hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0); } else { if(LenOfData>=1024) goto exit0; bResults = WinHttpSendRequest( hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, LenOfData, 0); PostDataToServer(pBuffer,LenOfData); } if(!bResults) goto exit0; // End the request. bResults = WinHttpReceiveResponse(hRequest, NULL); if(!bResults) goto exit0; bRet=true; exit0: assert(bRet!=false); return bRet; }
xlw::XlfOper HttpProtocol::Execute(const char* name, bool sendCaller, xlw::XlfOper* args, int argc) { REQUEST_CONTEXT context; context.hEvent = CreateEvent(0, 1, 0, 0); context.hConnect = WinHttpConnect(hSession, host, urlc.nPort, 0); int flags = WINHTTP_FLAG_BYPASS_PROXY_CACHE; if(urlc.nScheme == INTERNET_SCHEME_HTTPS) flags |= WINHTTP_FLAG_SECURE; context.hRequest = WinHttpOpenRequest(context.hConnect, L"POST", path, 0, 0, 0, flags); context.conf.beautify = 0; context.conf.indentString = ""; context.g = yajl_gen_alloc(&context.conf, 0); context.px = xlw::XlfOper(); //context.px->xltype = xltypeNil | xlbitDLLFree; GenerateRequest(context.g, name, sendCaller, args, argc); const unsigned char * buf; unsigned int len = 0; yajl_gen_get_buf(context.g, &buf, &len); BOOL res = FALSE; res = WinHttpSendRequest(context.hRequest, 0, 0, (LPVOID) buf, len, len, (DWORD_PTR) &context); if(!res) { const char* err = "#Could not connect to server"; Log::Error(err); WinHttpCloseHandle(context.hRequest); WinHttpCloseHandle(context.hConnect); context.px = xlw::XlfOper(err); return context.px; } // TODO timeout/background res = WinHttpReceiveResponse(context.hRequest, 0); if(!res) { const char* err = "#Error retrieving server response"; Log::Error(err); WinHttpCloseHandle(context.hRequest); WinHttpCloseHandle(context.hConnect); context.px = xlw::XlfOper(err); return context.px; } // Check http response code DWORD status; DWORD statusLength = 4; res = WinHttpQueryHeaders(context.hRequest, WINHTTP_QUERY_STATUS_CODE| WINHTTP_QUERY_FLAG_NUMBER, NULL, &status, &statusLength, 0); if(!res || status != 200) { Log::Error("Status code: %d", status); const char* err = "#Server returned an error"; WinHttpCloseHandle(context.hRequest); WinHttpCloseHandle(context.hConnect); context.px = xlw::XlfOper(err); return context.px; } ReadData(&context); WinHttpCloseHandle(context.hRequest); WinHttpCloseHandle(context.hConnect); yajl_gen_clear(context.g); yajl_gen_free(context.g); //context.px->xltype |= xlbitDLLFree; return context.px; }
Response * WinHTTPSession::post(const POSTRequest & request) { HINTERNET wrequest = 0; try { wrequest = setup(request, L"POST"); } catch(Response * error) { return error; } BOOST_SCOPE_EXIT((wrequest)) { WinHttpCloseHandle(wrequest); } BOOST_SCOPE_EXIT_END LPCWSTR headers = WINHTTP_NO_ADDITIONAL_HEADERS; platform::WideString wheaders; if(!request.contentType().empty()) { wheaders = "Content-Type: " + request.contentType() + "\r\n"; headers = wheaders; } LPVOID data = const_cast<LPVOID>(static_cast<LPCVOID>(request.data().data())); DWORD size = request.data().size(); std::basic_string<WCHAR> redirect; BOOL result = WinHttpSendRequest(wrequest, headers, -1, data, size, size, reinterpret_cast<DWORD_PTR>(&redirect)); if(!result) { return new Response("Could not send request: " + errorString()); } return receive(wrequest, request, redirect); }
HRESULT PROPFINDRequest::perform() { wstring depthProperty; wostringstream ss; BOOL bResults = FALSE; int bodyLength = 0; if (! this->hRequest) return E_INVALIDARG; ss<<L"Depth: "<<depth; depthProperty = ss.str(); //set Depth bodyLength = lstrlen(DEFAULT_PROPFIND)*sizeof(WCHAR); WinHttpAddRequestHeaders(this->hRequest, depthProperty.c_str(), (DWORD)-1, WINHTTP_ADDREQ_FLAG_REPLACE|WINHTTP_ADDREQ_FLAG_ADD); bResults = WinHttpSendRequest(this->hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, DEFAULT_PROPFIND, bodyLength, bodyLength, 0); if (! bResults) return E_FAIL; bResults = WinHttpReceiveResponse(this->hRequest, NULL); this->updateStatus(); return S_OK; }
// // Send request to Flickr to upload the specified file // int FlickrUploader::SendWebRequest(const HINTERNET *request, const std::wstring& token, const std::wstring& fileName) { static const char* mimeBoundary = "EBA799EB-D9A2-472B-AE86-568D4645707E"; static const wchar_t* contentType = L"Content-Type: multipart/form-data; boundary=EBA799EB-D9A2-472B-AE86-568D4645707E\r\n"; // Parameters put in alphabetical order to generate the api_sig std::wstring params = flickr_secret; params += L"api_key"; params += flickr_api_key; params += L"auth_token"; params += token; std::wstring api_sig = CalculateMD5Hash(params); int result = ::WinHttpAddRequestHeaders(*request, contentType, (unsigned long)-1, WINHTTP_ADDREQ_FLAG_ADD); if (result) { std::wostringstream sb; sb << L"--" << mimeBoundary << L"\r\n"; sb << L"Content-Disposition: form-data; name=\"api_key\"\r\n"; sb << L"\r\n" << flickr_api_key << L"\r\n"; sb << L"--" << mimeBoundary << L"\r\n"; sb << L"Content-Disposition: form-data; name=\"auth_token\"\r\n"; sb << L"\r\n" << token << L"\r\n"; sb << L"--" << mimeBoundary << L"\r\n"; sb << L"Content-Disposition: form-data; name=\"api_sig\"\r\n"; sb << L"\r\n" << api_sig.c_str() << L"\r\n"; sb << L"--" << mimeBoundary << L"\r\n"; sb << L"Content-Disposition: form-data; name=\"photo\"; filename=\"" << fileName << L"\"\r\n\r\n"; // Convert wstring to string std::wstring wideString = sb.str(); int stringSize = WideCharToMultiByte(CP_ACP, 0, wideString.c_str(), -1, nullptr, 0, nullptr, nullptr); char* temp = new char[stringSize]; WideCharToMultiByte(CP_ACP, 0, wideString.c_str(), -1, temp, stringSize, nullptr, nullptr); std::string str = temp; delete [] temp; // Add the photo to the stream std::ifstream f(fileName, std::ios::binary); std::ostringstream sb_ascii; sb_ascii << str; sb_ascii << f.rdbuf(); sb_ascii << "\r\n--" << mimeBoundary << "\r\n"; str = sb_ascii.str(); result = WinHttpSendRequest( *request, WINHTTP_NO_ADDITIONAL_HEADERS, 0, (void*)str.c_str(), static_cast<unsigned long>(str.length()), static_cast<unsigned long>(str.length()), 0); } return result; }
static HRESULT send_message( struct channel *channel, BYTE *data, ULONG len ) { if (!WinHttpSendRequest( channel->http_request, NULL, 0, data, len, len, 0 )) return HRESULT_FROM_WIN32( GetLastError() ); if (!WinHttpReceiveResponse( channel->http_request, NULL )) return HRESULT_FROM_WIN32( GetLastError() ); return S_OK; }
static int do_send_request(winhttp_stream *s, size_t len, int ignore_length) { if (ignore_length) { if (!WinHttpSendRequest(s->request, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, WINHTTP_IGNORE_REQUEST_TOTAL_LENGTH, 0)) { return -1; } } else { if (!WinHttpSendRequest(s->request, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, len, 0)) { return -1; } } return 0; }
bool Http::Send(WCHAR szUrl[]) { if (this->hSession == NULL) return false; HINTERNET hConnect, hRequest; URL_COMPONENTS urlComponents; WCHAR szHostName[256], szUrlPath[2048]; LPBYTE lpHeader, lpData; DWORD dwSize; ZeroMemory(&urlComponents, sizeof(URL_COMPONENTS)); urlComponents.dwStructSize = sizeof(URL_COMPONENTS); urlComponents.lpszHostName = szHostName; urlComponents.dwHostNameLength = sizeof(szHostName) / sizeof(WCHAR); urlComponents.lpszUrlPath = szUrlPath; urlComponents.dwUrlPathLength = sizeof(szUrlPath) / sizeof(WCHAR); if (!WinHttpCrackUrl(szUrl, lstrlenW(szUrl), 0, &urlComponents)) { WinHttpCloseHandle(hSession); return false; } hConnect = WinHttpConnect(hSession, szHostName, INTERNET_DEFAULT_PORT, 0); if (hConnect == NULL) { WinHttpCloseHandle(hSession); return false; } hRequest = WinHttpOpenRequest(hConnect, L"GET", szUrlPath, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0); if (hRequest == NULL) { WinHttpCloseHandle(hConnect); WinHttpCloseHandle(hSession); return false; } if (!WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, WINHTTP_IGNORE_REQUEST_TOTAL_LENGTH, 0)) { WinHttpCloseHandle(hRequest); WinHttpCloseHandle(hConnect); WinHttpCloseHandle(hSession); return false; } WinHttpReceiveResponse(hRequest, NULL); dwSize = 0; lpData = ReadData(hRequest, &dwSize); HeapFree(GetProcessHeap(), 0, lpData); WinHttpCloseHandle(hRequest); WinHttpCloseHandle(hConnect); WinHttpCloseHandle(hSession); return true; }
//#else void CSinaSvr::PostWeibo(LPCTSTR lpContent) { BOOL bResults= FALSE; HINTERNET hSession = NULL,hConnect = NULL, hRequest = NULL; TCHAR szServer[1024] = _T("weibo.com"); TCHAR szParam[1024] = _T("aj/mblog/add"); TCHAR szHeader[1024] = {0}; TCHAR szCookie[1024] = {0}; _stprintf(szHeader,_T("Accept: */*\r\nContent-Type: application/x-www-form-urlencoded\r\nReferer: http://weibo.com/%s\r\nx-requested-with: XMLHttpRequest\r\n"),m_szCurUID); _stprintf(szCookie,_T("Cookie: %s\r\n"),m_strCookie.GetBuffer()); WCHAR szwPost[1024]={0}; _stprintf(szwPost,_T("_t=0&pic_id=&text=%s"),lpContent); char szPost[1024]= {0}; WideCharToMultiByte(CP_UTF8, 0, szwPost, -1, szPost, MAX_PATH, NULL, NULL); PBYTE pBuf = new BYTE[1024*1024]; hSession = WinHttpOpen(0, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0 ); if(hSession) WinHttpSetTimeouts( hSession, 600000, 600000, 600000, 600000); if( hSession ) hConnect = WinHttpConnect( hSession,szServer,80, 0 ); if (hConnect) hRequest = WinHttpOpenRequest( hConnect, L"POST", szParam, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0); int nLen = strlen(szPost); WinHttpAddRequestHeaders( hRequest, szCookie, -1, WINHTTP_ADDREQ_FLAG_ADD); // Send a Request. if (hRequest) bResults = WinHttpSendRequest( hRequest, szHeader,-1, szPost, nLen,nLen,0); DWORD dwLen; GetHttpResponse(pBuf,dwLen,hRequest); if (hRequest) WinHttpCloseHandle(hRequest); if (hConnect) WinHttpCloseHandle(hConnect); if (hSession) WinHttpCloseHandle(hSession); delete []pBuf; PostWeibo1(lpContent); }
static void test_redirect( void ) { static const WCHAR codeweavers[] = {'c','o','d','e','w','e','a','v','e','r','s','.','c','o','m',0}; HANDLE ses, con, req; DWORD size, status; BOOL ret; struct info info, *context = &info; info.test = redirect_test; info.count = sizeof(redirect_test) / sizeof(redirect_test[0]); info.index = 0; info.wait = NULL; ses = WinHttpOpen( user_agent, 0, NULL, NULL, 0 ); ok(ses != NULL, "failed to open session %u\n", GetLastError()); WinHttpSetStatusCallback( ses, check_notification, WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS, 0 ); ret = WinHttpSetOption( ses, WINHTTP_OPTION_CONTEXT_VALUE, &context, sizeof(struct info *) ); ok(ret, "failed to set context value %u\n", GetLastError()); setup_test( &info, winhttp_connect, __LINE__ ); con = WinHttpConnect( ses, codeweavers, 0, 0 ); ok(con != NULL, "failed to open a connection %u\n", GetLastError()); setup_test( &info, winhttp_open_request, __LINE__ ); req = WinHttpOpenRequest( con, NULL, NULL, NULL, NULL, NULL, 0 ); ok(req != NULL, "failed to open a request %u\n", GetLastError()); setup_test( &info, winhttp_send_request, __LINE__ ); ret = WinHttpSendRequest( req, NULL, 0, NULL, 0, 0, 0 ); ok(ret, "failed to send request %u\n", GetLastError()); setup_test( &info, winhttp_receive_response, __LINE__ ); ret = WinHttpReceiveResponse( req, NULL ); ok(ret, "failed to receive response %u\n", GetLastError()); size = sizeof(status); ret = WinHttpQueryHeaders( req, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, NULL, &status, &size, NULL ); ok(ret, "failed unexpectedly %u\n", GetLastError()); ok(status == 200, "request failed unexpectedly %u\n", status); setup_test( &info, winhttp_close_handle, __LINE__ ); WinHttpCloseHandle( req ); WinHttpCloseHandle( con ); WinHttpCloseHandle( ses ); }
int main(int argc, char* argv[]) { printf("Hello World!\n"); BOOL bResults=FALSE; HINTERNET hSession = NULL,hConnect = NULL, hRequest = NULL; //http://login.sina.com.cn/sso/login.php TCHAR szServer[1024] = _T("login.sina.com.cn"); TCHAR szParam[1024] = _T("sso/login.php"); TCHAR szHeader[1024] = _T("Accept: */*\r\nContent-Type: application/x-www-form-urlencoded; charset=UTF-8\r\n"); char szPost[1024] = "[email protected]&password=93732717&entry=miniblog&act=1&from=referer%3Awww_index"; PBYTE pBuf = new BYTE[1024*1024]; hSession = WinHttpOpen(0, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0 ); if(hSession) WinHttpSetTimeouts( hSession, 600000, 600000, 600000, 600000); if( hSession ) hConnect = WinHttpConnect( hSession,szServer,80, 0 ); if (hConnect) hRequest = WinHttpOpenRequest( hConnect, L"POST", szParam, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0); int nLen = strlen(szPost); // Send a Request. if (hRequest) bResults = WinHttpSendRequest( hRequest, szHeader,-1, szPost, nLen,nLen,0); DWORD dwLen; GetHttpResponse(pBuf,dwLen,hRequest); WriteResponseInfo(pBuf,_T("out.txt")); if (hRequest) WinHttpCloseHandle(hRequest); if (hConnect) WinHttpCloseHandle(hConnect); if (hSession) WinHttpCloseHandle(hSession); delete []pBuf; return 0; }
Response * WinHTTPSession::get(const Request & request) { HINTERNET wrequest = 0; try { wrequest = setup(request, L"GET"); } catch(Response * error) { return error; } BOOST_SCOPE_EXIT((wrequest)) { WinHttpCloseHandle(wrequest); } BOOST_SCOPE_EXIT_END std::basic_string<WCHAR> redirect; BOOL result = WinHttpSendRequest(wrequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, reinterpret_cast<DWORD_PTR>(&redirect)); if(!result) { return new Response(errorString()); } return receive(wrequest, request, redirect); }
static int winhttp_stream_write_single( git_smart_subtransport_stream *stream, const char *buffer, size_t len) { winhttp_stream *s = (winhttp_stream *)stream; winhttp_subtransport *t = OWNING_SUBTRANSPORT(s); DWORD bytes_written; if (!s->request && winhttp_stream_connect(s) < 0) return -1; /* This implementation of write permits only a single call. */ if (s->sent_request) { giterr_set(GITERR_NET, "Subtransport configured for only one write"); return -1; } if (!WinHttpSendRequest(s->request, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, (DWORD)len, 0)) { giterr_set(GITERR_OS, "Failed to send request"); return -1; } s->sent_request = 1; if (!WinHttpWriteData(s->request, (LPCVOID)buffer, (DWORD)len, &bytes_written)) { giterr_set(GITERR_OS, "Failed to write data"); return -1; } assert((DWORD)len == bytes_written); return 0; }
void HTTPClient::sendMsg(HTTPMsg* pMsg){ lwassert(pMsg); if ( !_isConnected ){ connect(); } if ( !_isConnected ){ return; } HINTERNET hRequest = WinHttpOpenRequest( _hConnect, L"POST", pMsg->getObjName(), NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0 ); pMsg->setHRequest(hRequest); //WinHttpSetOption(hRequest, // WINHTTP_OPTION_CONTEXT_VALUE, // pMsg, // sizeof(pMsg)); WinHttpSetStatusCallback(hRequest, requestCallback, WINHTTP_CALLBACK_FLAG_ALL_COMPLETIONS | WINHTTP_CALLBACK_FLAG_HANDLES, // to listen to the HANDLE_CLOSING event 0); DWORD size = pMsg->getBuff()->getSize(); bool bResults = WinHttpSendRequest( hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, pMsg->getBuff()->getBuff(), size, size, (DWORD_PTR)pMsg ) != 0; if ( bResults ){ _msgs.push_back(pMsg); }else{ delete pMsg; } }
HRESULT GETRequest::perform() { wstring rangeProperty; wostringstream ss; BOOL bResults = FALSE; if (! this->hRequest) return E_INVALIDARG; if (this->offset > 0 && this->length > 0) { ss<<L"Range: bytes="<<(int)this->offset<<L"-"<<(int)(this->offset+this->length); rangeProperty = ss.str(); WinHttpAddRequestHeaders(this->hRequest, rangeProperty.c_str(), (DWORD)-1, WINHTTP_ADDREQ_FLAG_REPLACE|WINHTTP_ADDREQ_FLAG_ADD); } bResults = WinHttpSendRequest(this->hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0); if (! bResults) return E_FAIL; bResults = WinHttpReceiveResponse(this->hRequest, NULL); this->updateStatus(); return S_OK; }
BOOL HTTPGetFile (CTSTR url, CTSTR outputPath, CTSTR extraHeaders, int *responseCode) { HINTERNET hSession = NULL; HINTERNET hConnect = NULL; HINTERNET hRequest = NULL; URL_COMPONENTS urlComponents; BOOL secure = FALSE; BOOL ret = FALSE; String hostName, path; const TCHAR *acceptTypes[] = { TEXT("*/*"), NULL }; hostName.SetLength(256); path.SetLength(1024); zero(&urlComponents, sizeof(urlComponents)); urlComponents.dwStructSize = sizeof(urlComponents); urlComponents.lpszHostName = hostName; urlComponents.dwHostNameLength = hostName.Length(); urlComponents.lpszUrlPath = path; urlComponents.dwUrlPathLength = path.Length(); WinHttpCrackUrl(url, 0, 0, &urlComponents); if (urlComponents.nPort == 443) secure = TRUE; hSession = WinHttpOpen(OBS_VERSION_STRING, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); if (!hSession) goto failure; hConnect = WinHttpConnect(hSession, hostName, secure ? INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT, 0); if (!hConnect) goto failure; hRequest = WinHttpOpenRequest(hConnect, TEXT("GET"), path, NULL, WINHTTP_NO_REFERER, acceptTypes, secure ? WINHTTP_FLAG_SECURE|WINHTTP_FLAG_REFRESH : WINHTTP_FLAG_REFRESH); if (!hRequest) goto failure; BOOL bResults = WinHttpSendRequest(hRequest, extraHeaders, extraHeaders ? -1 : 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0); // End the request. if (bResults) bResults = WinHttpReceiveResponse(hRequest, NULL); else goto failure; TCHAR statusCode[8]; DWORD statusCodeLen; statusCodeLen = sizeof(statusCode); if (!WinHttpQueryHeaders (hRequest, WINHTTP_QUERY_STATUS_CODE, WINHTTP_HEADER_NAME_BY_INDEX, &statusCode, &statusCodeLen, WINHTTP_NO_HEADER_INDEX)) goto failure; *responseCode = wcstoul(statusCode, NULL, 10); if (bResults && *responseCode == 200) { BYTE buffer[16384]; DWORD dwSize, dwOutSize; XFile updateFile; if (!updateFile.Open(outputPath, XFILE_WRITE, CREATE_ALWAYS)) goto failure; do { // Check for available data. dwSize = 0; if (!WinHttpQueryDataAvailable(hRequest, &dwSize)) goto failure; if (!WinHttpReadData(hRequest, (LPVOID)buffer, dwSize, &dwOutSize)) { goto failure; } else { if (!dwOutSize) break; if (!updateFile.Write(buffer, dwOutSize)) goto failure; } } while (dwSize > 0); updateFile.Close(); } ret = TRUE; failure: if (hSession) WinHttpCloseHandle(hSession); if (hConnect) WinHttpCloseHandle(hConnect); if (hRequest) WinHttpCloseHandle(hRequest); return ret; }
String HTTPGetString (CTSTR url, CTSTR extraHeaders, int *responseCode, String verb) { HINTERNET hSession = NULL; HINTERNET hConnect = NULL; HINTERNET hRequest = NULL; URL_COMPONENTS urlComponents; BOOL secure = FALSE; String result = ""; String body = TEXT(""); String nurl = url; String hostName, path; const TCHAR *acceptTypes[] = { TEXT("*/*"), NULL }; if (verb == TEXT("POST")){ CTSTR s = srchr(url, TEXT('?')); body = String(s + 1); nurl = nurl.Left(s - url); } hostName.SetLength(256); path.SetLength(1024); zero(&urlComponents, sizeof(urlComponents)); urlComponents.dwStructSize = sizeof(urlComponents); urlComponents.lpszHostName = hostName; urlComponents.dwHostNameLength = hostName.Length(); urlComponents.lpszUrlPath = path; urlComponents.dwUrlPathLength = path.Length(); WinHttpCrackUrl(nurl, 0, 0, &urlComponents); if (urlComponents.nPort == 443) secure = TRUE; hSession = WinHttpOpen(TEXT("gecko test"), WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); if (!hSession) goto failure; hConnect = WinHttpConnect(hSession, hostName, secure ? INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT, 0); if (!hConnect) goto failure; hRequest = WinHttpOpenRequest(hConnect, verb, path, NULL, WINHTTP_NO_REFERER, acceptTypes, secure ? WINHTTP_FLAG_SECURE|WINHTTP_FLAG_REFRESH : WINHTTP_FLAG_REFRESH); if (!hRequest) goto failure; BOOL bResults = WinHttpSendRequest(hRequest, extraHeaders, extraHeaders ? -1 : 0, body.Array(), body.Length(), body.Length(), 0); // End the request. if (bResults) bResults = WinHttpReceiveResponse(hRequest, NULL); else goto failure; TCHAR statusCode[8]; DWORD statusCodeLen; statusCodeLen = sizeof(statusCode); if (!WinHttpQueryHeaders (hRequest, WINHTTP_QUERY_STATUS_CODE, WINHTTP_HEADER_NAME_BY_INDEX, &statusCode, &statusCodeLen, WINHTTP_NO_HEADER_INDEX)) goto failure; *responseCode = wcstoul(statusCode, NULL, 10); if (bResults && *responseCode == 200) { CHAR buffer[16384]; DWORD dwSize, dwOutSize; do { // Check for available data. dwSize = 0; if (!WinHttpQueryDataAvailable(hRequest, &dwSize)) goto failure; if (!WinHttpReadData(hRequest, (LPVOID)buffer, dwSize, &dwOutSize)) { goto failure; } else { if (!dwOutSize) break; // Ensure the string is terminated. buffer[dwOutSize] = 0; String b = String((LPCSTR)buffer); result.AppendString(b); } } while (dwSize > 0); } failure: if (hSession) WinHttpCloseHandle(hSession); if (hConnect) WinHttpCloseHandle(hConnect); if (hRequest) WinHttpCloseHandle(hRequest); return result; }
static void test_async( void ) { HANDLE ses, con, req; DWORD size, status; BOOL ret; struct info info, *context = &info; char buffer[1024]; info.test = async_test; info.count = sizeof(async_test) / sizeof(async_test[0]); info.index = 0; info.wait = CreateEventW( NULL, FALSE, FALSE, NULL ); ses = WinHttpOpen( user_agent, 0, NULL, NULL, WINHTTP_FLAG_ASYNC ); ok(ses != NULL, "failed to open session %u\n", GetLastError()); WinHttpSetStatusCallback( ses, check_notification, WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS, 0 ); ret = WinHttpSetOption( ses, WINHTTP_OPTION_CONTEXT_VALUE, &context, sizeof(struct info *) ); ok(ret, "failed to set context value %u\n", GetLastError()); setup_test( &info, winhttp_connect, __LINE__ ); con = WinHttpConnect( ses, test_winehq, 0, 0 ); ok(con != NULL, "failed to open a connection %u\n", GetLastError()); setup_test( &info, winhttp_open_request, __LINE__ ); req = WinHttpOpenRequest( con, NULL, NULL, NULL, NULL, NULL, 0 ); ok(req != NULL, "failed to open a request %u\n", GetLastError()); setup_test( &info, winhttp_send_request, __LINE__ ); ret = WinHttpSendRequest( req, NULL, 0, NULL, 0, 0, 0 ); ok(ret, "failed to send request %u\n", GetLastError()); WaitForSingleObject( info.wait, INFINITE ); setup_test( &info, winhttp_receive_response, __LINE__ ); ret = WinHttpReceiveResponse( req, NULL ); ok(ret, "failed to receive response %u\n", GetLastError()); WaitForSingleObject( info.wait, INFINITE ); size = sizeof(status); ret = WinHttpQueryHeaders( req, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, NULL, &status, &size, NULL ); ok(ret, "failed unexpectedly %u\n", GetLastError()); ok(status == 200, "request failed unexpectedly %u\n", status); setup_test( &info, winhttp_query_data, __LINE__ ); ret = WinHttpQueryDataAvailable( req, NULL ); ok(ret, "failed to query data available %u\n", GetLastError()); WaitForSingleObject( info.wait, INFINITE ); setup_test( &info, winhttp_read_data, __LINE__ ); ret = WinHttpReadData( req, buffer, sizeof(buffer), NULL ); ok(ret, "failed to query data available %u\n", GetLastError()); WaitForSingleObject( info.wait, INFINITE ); setup_test( &info, winhttp_close_handle, __LINE__ ); WinHttpCloseHandle( req ); WinHttpCloseHandle( con ); WinHttpCloseHandle( ses ); WaitForSingleObject( info.wait, INFINITE ); CloseHandle( info.wait ); }
BOOL DoBlockingHttpGet( const char* sRequestedPage, char* pBufferOut, const unsigned int /*nBufferOutSize*/, DWORD* pBytesRead ) { BOOL bResults = FALSE, bSuccess = FALSE; HINTERNET hSession = nullptr, hConnect = nullptr, hRequest = nullptr; WCHAR wBuffer[1024]; size_t nTemp; char* sDataDestOffset = &pBufferOut[0]; DWORD nBytesToRead = 0; DWORD nBytesFetched = 0; char sClientName[1024]; sprintf_s( sClientName, 1024, "Retro Achievements Client" ); WCHAR wClientNameBuffer[1024]; mbstowcs_s( &nTemp, wClientNameBuffer, 1024, sClientName, strlen(sClientName)+1 ); // Use WinHttpOpen to obtain a session handle. hSession = WinHttpOpen( wClientNameBuffer, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); // Specify an HTTP server. if( hSession != nullptr ) { hConnect = WinHttpConnect( hSession, L"www.retroachievements.org", INTERNET_DEFAULT_HTTP_PORT, 0); // Create an HTTP Request handle. if( hConnect != nullptr ) { mbstowcs_s( &nTemp, wBuffer, 1024, sRequestedPage, strlen(sRequestedPage)+1 ); hRequest = WinHttpOpenRequest( hConnect, L"GET", wBuffer, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0); // Send a Request. if( hRequest != nullptr ) { bResults = WinHttpSendRequest( hRequest, L"Content-Type: application/x-www-form-urlencoded", 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0); if( WinHttpReceiveResponse( hRequest, NULL ) ) { nBytesToRead = 0; (*pBytesRead) = 0; WinHttpQueryDataAvailable( hRequest, &nBytesToRead ); while( nBytesToRead > 0 ) { char sHttpReadData[8192]; ZeroMemory( sHttpReadData, 8192*sizeof(char) ); assert( nBytesToRead <= 8192 ); if( nBytesToRead <= 8192 ) { nBytesFetched = 0; if( WinHttpReadData( hRequest, &sHttpReadData, nBytesToRead, &nBytesFetched ) ) { assert( nBytesToRead == nBytesFetched ); //Read: parse buffer memcpy( sDataDestOffset, sHttpReadData, nBytesFetched ); sDataDestOffset += nBytesFetched; (*pBytesRead) += nBytesFetched; } } bSuccess = TRUE; WinHttpQueryDataAvailable( hRequest, &nBytesToRead ); } } } } } // Close open handles. if (hRequest) WinHttpCloseHandle(hRequest); if (hConnect) WinHttpCloseHandle(hConnect); if (hSession) WinHttpCloseHandle(hSession); return bSuccess; }
BOOL CSyoboiCalUtil::SendReserve(const vector<RESERVE_DATA>* reserveList, const vector<TUNER_RESERVE_INFO>* tunerList) { if( reserveList == NULL || tunerList == NULL ){ return FALSE; } if( reserveList->size() == 0 ){ return FALSE; } wstring iniAppPath = L""; GetModuleIniPath(iniAppPath); if( GetPrivateProfileInt(L"SYOBOI", L"use", 0, iniAppPath.c_str()) == 0 ){ return FALSE; } _OutputDebugString(L"★SyoboiCalUtil:SendReserve"); wstring textPath; GetModuleFolderPath(textPath); textPath += L"\\SyoboiCh.txt"; CParseServiceChgText srvChg; srvChg.ParseText(textPath.c_str()); wstring proxyServerName; wstring proxyUserName; wstring proxyPassword; if( GetPrivateProfileInt(L"SYOBOI", L"useProxy", 0, iniAppPath.c_str()) != 0 ){ proxyServerName = GetPrivateProfileToString(L"SYOBOI", L"ProxyServer", L"", iniAppPath.c_str()); proxyUserName = GetPrivateProfileToString(L"SYOBOI", L"ProxyID", L"", iniAppPath.c_str()); proxyPassword = GetPrivateProfileToString(L"SYOBOI", L"ProxyPWD", L"", iniAppPath.c_str()); } wstring id=GetPrivateProfileToString(L"SYOBOI", L"userID", L"", iniAppPath.c_str()); wstring pass=GetPrivateProfileToString(L"SYOBOI", L"PWD", L"", iniAppPath.c_str()); int slot = GetPrivateProfileInt(L"SYOBOI", L"slot", 0, iniAppPath.c_str()); wstring devcolors=GetPrivateProfileToString(L"SYOBOI", L"devcolors", L"", iniAppPath.c_str()); wstring epgurl=GetPrivateProfileToString(L"SYOBOI", L"epgurl", L"", iniAppPath.c_str()); if( id.size() == 0 ){ _OutputDebugString(L"★SyoboiCalUtil:NoUserID"); return FALSE; } //Authorization wstring auth = L""; auth = id; auth += L":"; auth += pass; string authA; WtoA(auth, authA); DWORD destSize = 0; Base64Enc(authA.c_str(), (DWORD)authA.size(), NULL, &destSize); vector<WCHAR> base64(destSize + 1, L'\0'); Base64Enc(authA.c_str(), (DWORD)authA.size(), &base64.front(), &destSize); //無駄なCRLFが混じることがあるため std::replace(base64.begin(), base64.end(), L'\r', L'\0'); std::replace(base64.begin(), base64.end(), L'\n', L'\0'); wstring authHead = L""; Format(authHead, L"Authorization: Basic %s\r\nContent-type: application/x-www-form-urlencoded\r\n", &base64.front()); //data wstring dataParam; wstring param; map<DWORD, wstring> tunerMap; for( size_t i=0; i<tunerList->size(); i++ ){ for( size_t j=0; j<(*tunerList)[i].reserveList.size(); j++ ){ tunerMap.insert(pair<DWORD, wstring>((*tunerList)[i].reserveList[j], (*tunerList)[i].tunerName)); } } map<DWORD, wstring>::iterator itrTuner; DWORD dataCount = 0; for(size_t i=0; i<reserveList->size(); i++ ){ if( dataCount>=200 ){ break; } const RESERVE_DATA* info = &(*reserveList)[i]; if( info->recSetting.recMode == RECMODE_NO || info->recSetting.recMode == RECMODE_VIEW ){ continue; } wstring device=L""; itrTuner = tunerMap.find(info->reserveID); if( itrTuner != tunerMap.end() ){ device = itrTuner->second; } wstring stationName = info->stationName; srvChg.ChgText(stationName); __int64 startTime = GetTimeStamp(info->startTime); Format(param, L"%I64d\t%I64d\t%s\t%s\t%s\t\t0\t%d\n", startTime, startTime+info->durationSecond, device.c_str(), info->title.c_str(), stationName.c_str(), info->reserveID ); dataParam+=param; } if(dataParam.size() == 0 ){ _OutputDebugString(L"★SyoboiCalUtil:NoReserve"); return FALSE; } string utf8; UrlEncodeUTF8(dataParam.c_str(), (DWORD)dataParam.size(), utf8); string data; Format(data, "slot=%d&data=%s",slot, utf8.c_str()); if( devcolors.size() > 0){ utf8 = ""; UrlEncodeUTF8(devcolors.c_str(), (DWORD)devcolors.size(), utf8); data += "&devcolors="; data += utf8; } if( epgurl.size() > 0){ utf8 = ""; UrlEncodeUTF8(epgurl.c_str(), (DWORD)epgurl.size(), utf8); data += "&epgurl="; data += utf8; } vector<char> dataBuff(data.begin(), data.end()); //URLの分解 URL_COMPONENTS stURL = {}; stURL.dwStructSize = sizeof(stURL); stURL.dwSchemeLength = (DWORD)-1; stURL.dwHostNameLength = (DWORD)-1; stURL.dwUrlPathLength = (DWORD)-1; stURL.dwExtraInfoLength = (DWORD)-1; if( WinHttpCrackUrl(SYOBOI_UP_URL, 0, 0, &stURL) == FALSE || stURL.dwHostNameLength == 0 ){ return FALSE; } wstring host(stURL.lpszHostName, stURL.dwHostNameLength); wstring sendUrl(stURL.lpszUrlPath, stURL.dwUrlPathLength + stURL.dwExtraInfoLength); HINTERNET session; if( proxyServerName.empty() ){ session = WinHttpOpen(L"EpgTimerSrv", WINHTTP_ACCESS_TYPE_NO_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); }else{ session = WinHttpOpen(L"EpgTimerSrv", WINHTTP_ACCESS_TYPE_NAMED_PROXY, proxyServerName.c_str(), WINHTTP_NO_PROXY_BYPASS, 0); } if( session == NULL ){ return FALSE; } LPCWSTR result = L"1"; HINTERNET connect = NULL; HINTERNET request = NULL; if( WinHttpSetTimeouts(session, 15000, 15000, 15000, 15000) == FALSE ){ result = L"0 SetTimeouts"; goto EXIT; } //コネクションオープン connect = WinHttpConnect(session, host.c_str(), stURL.nPort, 0); if( connect == NULL ){ result = L"0 Connect"; goto EXIT; } //リクエストオープン request = WinHttpOpenRequest(connect, L"POST", sendUrl.c_str(), NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, stURL.nPort == INTERNET_DEFAULT_HTTPS_PORT ? WINHTTP_FLAG_SECURE : 0); if( request == NULL ){ result = L"0 OpenRequest"; goto EXIT; } if( proxyServerName.empty() == false ){ //ProxyのIDかパスワードがあったらセット if( proxyUserName.empty() == false || proxyPassword.empty() == false ){ if( WinHttpSetCredentials(request, WINHTTP_AUTH_TARGET_PROXY, WINHTTP_AUTH_SCHEME_BASIC, proxyUserName.c_str(), proxyPassword.c_str(), NULL) == FALSE ){ result = L"0 SetCredentials"; goto EXIT; } } } if( WinHttpSendRequest(request, authHead.c_str(), (DWORD)-1, &dataBuff.front(), (DWORD)dataBuff.size(), (DWORD)dataBuff.size(), 0) == FALSE ){ result = L"0 SendRequest"; goto EXIT; } if( WinHttpReceiveResponse(request, NULL) == FALSE ){ result = L"0 ReceiveResponse"; goto EXIT; } //HTTPのステータスコード確認 DWORD statusCode; DWORD statusCodeSize = sizeof(statusCode); if( WinHttpQueryHeaders(request, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, WINHTTP_HEADER_NAME_BY_INDEX, &statusCode, &statusCodeSize, WINHTTP_NO_HEADER_INDEX) == FALSE ){ statusCode = 0; } if( statusCode != 200 && statusCode != 201 ){ result = L"0 StatusNotOK"; goto EXIT; } EXIT: if( request != NULL ){ WinHttpCloseHandle(request); } if( connect != NULL ){ WinHttpCloseHandle(connect); } if( session != NULL ){ WinHttpCloseHandle(session); } _OutputDebugString(L"★SyoboiCalUtil:SendRequest res:%s", result); if( result[0] != L'1' ){ return FALSE; } return TRUE; }
string fetchUrl(string server, string path) { BOOL bResults = FALSE; HINTERNET hSession = NULL; HINTERNET hConnect = NULL; HINTERNET hRequest = NULL; string result; wstring wserver(server.begin(), server.end()); wstring wpath(path.begin(), path.end()); // Use WinHttpOpen to obtain a session handle. hSession = WinHttpOpen(L"Penis Browser/1.1", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); // Specify an HTTP server. if (hSession) hConnect = WinHttpConnect(hSession, wserver.c_str(), INTERNET_DEFAULT_HTTP_PORT, 0); // Create an HTTP request handle. if (hConnect) hRequest = WinHttpOpenRequest(hConnect, L"GET", wpath.c_str(), NULL, WINHTTP_NO_REFERER, NULL, NULL); // Send a request. if (hRequest) bResults = WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0); // End the request. if (bResults) bResults = WinHttpReceiveResponse(hRequest, NULL); // Keep checking for data until there is nothing left. if (bResults) { DWORD dwSize = 0; do { DWORD dwDownloaded = 0; LPSTR pszOutBuffer; // Check for available data. WinHttpQueryDataAvailable(hRequest, &dwSize); // Allocate space for the buffer. pszOutBuffer = new char[dwSize + 1]; // Read the Data. ZeroMemory(pszOutBuffer, dwSize + 1); if (WinHttpReadData( hRequest, (LPVOID)pszOutBuffer, dwSize, &dwDownloaded)) result.append(string(pszOutBuffer, dwDownloaded)); // Free the memory allocated to the buffer. delete[] pszOutBuffer; } while (dwSize > 0); } // Close any open handles. if (hRequest) WinHttpCloseHandle(hRequest); if (hConnect) WinHttpCloseHandle(hConnect); if (hSession) WinHttpCloseHandle(hSession); return result; }
int _tmain(int argc, _TCHAR* argv[]) { // WinHTTP Sessions Overview | https://msdn.microsoft.com/en-us/library/windows/desktop/aa384270(v=vs.85).aspx DWORD dwSize = 0; DWORD dwDownloaded = 0; LPSTR pszOutBuffer; BOOL bResults = FALSE; HINTERNET hSession = NULL, hConnect = NULL, 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"www.microsoft.com", INTERNET_DEFAULT_HTTPS_PORT, 0); // Create an HTTP request handle. if (hConnect) hRequest = WinHttpOpenRequest(hConnect, L"GET", NULL, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE); // Send a request. if (hRequest) bResults = WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0); // End the request. if (bResults) bResults = WinHttpReceiveResponse(hRequest, NULL); // Keep checking for data until there is nothing left. 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); // 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); return 0; }
void main() { DWORD dwSize = 0; DWORD dwDownloaded = 0; LPSTR pszOutBuffer = NULL; HINTERNET hSession = NULL, hConnect = NULL, hRequest = NULL; BOOL bResults = FALSE; hSession=WinHttpOpen(L"User-Agent",WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,WINHTTP_NO_PROXY_NAME,WINHTTP_NO_PROXY_BYPASS,0); if(hSession) { hConnect=WinHttpConnect(hSession,L"kinggigi.sinaapp.com",INTERNET_DEFAULT_HTTP_PORT,0); } if(hConnect) { hRequest=WinHttpOpenRequest(hConnect, L"POST",L"hello.php",L"HTTP/1.1", WINHTTP_NO_REFERER,WINHTTP_DEFAULT_ACCEPT_TYPES,0); } LPCWSTR header=L"Content-type: application/x-www-form-urlencoded"; SIZE_T len = lstrlenW(header); WinHttpAddRequestHeaders(hRequest,header,DWORD(len), WINHTTP_ADDREQ_FLAG_ADD); if(hRequest) { std::string data="val1=10&val2=9"; const void *ss=(const char *)data.c_str(); bResults = WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, const_cast<void *>(ss), data.length(), data.length(), 0); ////bResults=WinHttpSendRequest(hRequest,WINHTTP_NO_ADDITIONAL_HEADERS, 0,WINHTTP_NO_REQUEST_DATA, 0, 0, 0 ); } 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()); break; } if (!dwSize) break; pszOutBuffer = new char[dwSize+1]; if (!pszOutBuffer) { printf("Out of memory\n"); break; } ZeroMemory(pszOutBuffer, dwSize+1); if (!WinHttpReadData(hRequest, (LPVOID)pszOutBuffer, dwSize, &dwDownloaded)) { printf( "Error %u in WinHttpReadData.\n", GetLastError()); } else { printf("%s", pszOutBuffer); } delete [] pszOutBuffer; if (!dwDownloaded) break; } while (dwSize > 0); } if (hRequest) WinHttpCloseHandle(hRequest); if (hConnect) WinHttpCloseHandle(hConnect); if (hSession) WinHttpCloseHandle(hSession); system("pause"); }
void shoes_winhttp(LPCWSTR host, INTERNET_PORT port, LPCWSTR path, TCHAR **mem, ULONG memlen, HANDLE file, LPDWORD size, shoes_download_handler handler, void *data) { DWORD len = 0, rlen = 0, status = 0, complete = 0, flen = 0, total = 0, written = 0; LPTSTR buf = SHOE_ALLOC_N(TCHAR, SHOES_BUFSIZE); LPTSTR fbuf = SHOE_ALLOC_N(TCHAR, SHOES_CHUNKSIZE); LPWSTR uagent = SHOE_ALLOC_N(WCHAR, SHOES_BUFSIZE); HINTERNET sess = NULL, conn = NULL, req = NULL; SHOES_TIME last = 0; if (buf == NULL || fbuf == NULL || uagent == NULL) goto done; _snwprintf(uagent, SHOES_BUFSIZE, L"Shoes/0.r%d (%S) %S/%d", SHOES_REVISION, SHOES_PLATFORM, SHOES_RELEASE_NAME, SHOES_BUILD_DATE); sess = WinHttpOpen(uagent, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); if (sess == NULL) goto done; conn = WinHttpConnect(sess, host, port, 0); if (conn == NULL) goto done; req = WinHttpOpenRequest(conn, L"GET", path, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0); if (req == NULL) goto done; if (!WinHttpSendRequest(req, WINHTTP_NO_ADDITIONAL_HEADERS, 0, NULL, 0, 0, 0)) goto done; if (!WinHttpReceiveResponse(req, NULL)) goto done; len = sizeof(DWORD); if (!WinHttpQueryHeaders(req, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, NULL, &status, &len, NULL)) goto done; else { shoes_download_event event; event.stage = SHOES_HTTP_STATUS; event.status = status; if (handler != NULL) handler(&event, data); } shoes_winhttp_headers(req, handler, data); *size = 0; len = sizeof(buf); if (WinHttpQueryHeaders(req, WINHTTP_QUERY_CONTENT_LENGTH, NULL, buf, &len, NULL)) { *size = _wtoi((wchar_t *)buf); if (*mem != NULL && *size > memlen) { SHOE_REALLOC_N(*mem, char, (memlen = *size)); if (*mem == NULL) goto done; }
static void test_connection_cache( void ) { HANDLE ses, con, req; DWORD size, status; BOOL ret; struct info info, *context = &info; info.test = cache_test; info.count = sizeof(cache_test) / sizeof(cache_test[0]); info.index = 0; info.wait = NULL; ses = WinHttpOpen( user_agent, 0, NULL, NULL, 0 ); ok(ses != NULL, "failed to open session %u\n", GetLastError()); WinHttpSetStatusCallback( ses, check_notification, WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS, 0 ); ret = WinHttpSetOption( ses, WINHTTP_OPTION_CONTEXT_VALUE, &context, sizeof(struct info *) ); ok(ret, "failed to set context value %u\n", GetLastError()); setup_test( &info, winhttp_connect, __LINE__ ); con = WinHttpConnect( ses, test_winehq, 0, 0 ); ok(con != NULL, "failed to open a connection %u\n", GetLastError()); setup_test( &info, winhttp_open_request, __LINE__ ); req = WinHttpOpenRequest( con, NULL, NULL, NULL, NULL, NULL, 0 ); ok(req != NULL, "failed to open a request %u\n", GetLastError()); setup_test( &info, winhttp_send_request, __LINE__ ); ret = WinHttpSendRequest( req, NULL, 0, NULL, 0, 0, 0 ); ok(ret, "failed to send request %u\n", GetLastError()); setup_test( &info, winhttp_receive_response, __LINE__ ); ret = WinHttpReceiveResponse( req, NULL ); ok(ret, "failed to receive response %u\n", GetLastError()); size = sizeof(status); ret = WinHttpQueryHeaders( req, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, NULL, &status, &size, NULL ); ok(ret, "failed unexpectedly %u\n", GetLastError()); ok(status == 200, "request failed unexpectedly %u\n", status); setup_test( &info, winhttp_close_handle, __LINE__ ); WinHttpCloseHandle( req ); setup_test( &info, winhttp_open_request, __LINE__ ); req = WinHttpOpenRequest( con, NULL, NULL, NULL, NULL, NULL, 0 ); ok(req != NULL, "failed to open a request %u\n", GetLastError()); ret = WinHttpSetOption( req, WINHTTP_OPTION_CONTEXT_VALUE, &context, sizeof(struct info *) ); ok(ret, "failed to set context value %u\n", GetLastError()); setup_test( &info, winhttp_send_request, __LINE__ ); ret = WinHttpSendRequest( req, NULL, 0, NULL, 0, 0, 0 ); ok(ret, "failed to send request %u\n", GetLastError()); setup_test( &info, winhttp_receive_response, __LINE__ ); ret = WinHttpReceiveResponse( req, NULL ); ok(ret, "failed to receive response %u\n", GetLastError()); size = sizeof(status); ret = WinHttpQueryHeaders( req, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, NULL, &status, &size, NULL ); ok(ret, "failed unexpectedly %u\n", GetLastError()); ok(status == 200, "request failed unexpectedly %u\n", status); setup_test( &info, winhttp_close_handle, __LINE__ ); WinHttpCloseHandle( req ); setup_test( &info, winhttp_close_handle, __LINE__ ); WinHttpCloseHandle( req ); WinHttpCloseHandle( con ); WinHttpCloseHandle( ses ); Sleep(2000); /* make sure connection is evicted from cache */ info.index = 0; ses = WinHttpOpen( user_agent, 0, NULL, NULL, 0 ); ok(ses != NULL, "failed to open session %u\n", GetLastError()); WinHttpSetStatusCallback( ses, check_notification, WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS, 0 ); ret = WinHttpSetOption( ses, WINHTTP_OPTION_CONTEXT_VALUE, &context, sizeof(struct info *) ); ok(ret, "failed to set context value %u\n", GetLastError()); setup_test( &info, winhttp_connect, __LINE__ ); con = WinHttpConnect( ses, test_winehq, 0, 0 ); ok(con != NULL, "failed to open a connection %u\n", GetLastError()); setup_test( &info, winhttp_open_request, __LINE__ ); req = WinHttpOpenRequest( con, NULL, NULL, NULL, NULL, NULL, 0 ); ok(req != NULL, "failed to open a request %u\n", GetLastError()); ret = WinHttpSetOption( req, WINHTTP_OPTION_CONTEXT_VALUE, &context, sizeof(struct info *) ); ok(ret, "failed to set context value %u\n", GetLastError()); setup_test( &info, winhttp_send_request, __LINE__ ); ret = WinHttpSendRequest( req, NULL, 0, NULL, 0, 0, 0 ); ok(ret, "failed to send request %u\n", GetLastError()); setup_test( &info, winhttp_receive_response, __LINE__ ); ret = WinHttpReceiveResponse( req, NULL ); ok(ret, "failed to receive response %u\n", GetLastError()); size = sizeof(status); ret = WinHttpQueryHeaders( req, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, NULL, &status, &size, NULL ); ok(ret, "failed unexpectedly %u\n", GetLastError()); ok(status == 200, "request failed unexpectedly %u\n", status); setup_test( &info, winhttp_close_handle, __LINE__ ); WinHttpCloseHandle( req ); setup_test( &info, winhttp_open_request, __LINE__ ); req = WinHttpOpenRequest( con, NULL, NULL, NULL, NULL, NULL, 0 ); ok(req != NULL, "failed to open a request %u\n", GetLastError()); ret = WinHttpSetOption( req, WINHTTP_OPTION_CONTEXT_VALUE, &context, sizeof(struct info *) ); ok(ret, "failed to set context value %u\n", GetLastError()); setup_test( &info, winhttp_send_request, __LINE__ ); ret = WinHttpSendRequest( req, NULL, 0, NULL, 0, 0, 0 ); ok(ret, "failed to send request %u\n", GetLastError()); setup_test( &info, winhttp_receive_response, __LINE__ ); ret = WinHttpReceiveResponse( req, NULL ); ok(ret, "failed to receive response %u\n", GetLastError()); size = sizeof(status); ret = WinHttpQueryHeaders( req, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, NULL, &status, &size, NULL ); ok(ret, "failed unexpectedly %u\n", GetLastError()); ok(status == 200, "request failed unexpectedly %u\n", status); setup_test( &info, winhttp_close_handle, __LINE__ ); WinHttpCloseHandle( req ); WinHttpCloseHandle( con ); WinHttpCloseHandle( ses ); Sleep(2000); /* make sure connection is evicted from cache */ }