Http Wrapper vs2008工程

http://files.cnblogs.com/files/kekec2/WinHttpClient_20100921.zip.gif

http://www.codeproject.com/Articles/66625/A-Fully-Featured-Windows-HTTP-Wrapper-in-C

Features

  • Cookies supported
  • Proxy supported
  • GETPOST methods supported
  • Request headers customization supported
  • Disable automatic redirection supported
  • HTTPS supported
  • Receive progress supported
  • Some other features

Examples

Simple Get Request

Get request is the most common request. Browsing a web page causes one or several Get requests.

Hide   Copy Code

// Set URL.
WinHttpClient client(L"http://www.codeproject.com/");

// Send HTTP request, a GET request by default.
client.SendHttpRequest();

// The response header.
wstring httpResponseHeader = client.GetResponseHeader();

// The response content.
wstring httpResponseContent = client.GetResponseContent();

Simple Post Request

Post request usually occurs while logging in or posting a thread.

Hide   Copy Code

WinHttpClient client(L"http://www.codeproject.com/");

// Set post data.
string data = "title=A_NEW_THREAD&content=This_is_a_new_thread.";
client.SetAdditionalDataToSend((BYTE *)data.c_str(), data.size());

// Set request headers.
wchar_t szSize[50] = L"";
swprintf_s(szSize, L"%d", data.size());
wstring headers = L"Content-Length: ";
headers += szSize;
headers += L"\r\nContent-Type: application/x-www-form-urlencoded\r\n";
client.SetAdditionalRequestHeaders(headers);

// Send HTTP post request.
client.SendHttpRequest(L"POST");

wstring httpResponseHeader = client.GetResponseHeader();
wstring httpResponseContent = client.GetResponseContent();

Getting Request‘s Progress

You can specify a callback function to get the request‘s progress.

Hide   Copy Code

// Progress - finished percentage.
bool ProgressProc(double progress)
{
    wprintf(L"Current progress: %-.1f%%\r\n", progress);
    return true;
}

void ProgressTest(void)
{
    // Set URL and call back function.
    WinHttpClient client(L"http://www.codeproject.com/", ProgressProc);
    client.SendHttpRequest();
    wstring httpResponseHeader = client.GetResponseHeader();
    wstring httpResponseContent = client.GetResponseContent();
}

Specifying the User Agent

User agent is a string used by the clients to identify themselves to the web server so that the server can tell which client software you use, Internet Explorer 8, Chrome or FireFox. You can specify the user agent to pretend to be Internet Explorer 8 to fool the web server because sometimes the server only supports Internet Explorer 8.

Hide   Copy Code

WinHttpClient client(L"http://www.codeproject.com/");

// Set the user agent to the same as Internet Explorer 8.
client.SetUserAgent(L"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1;...)");

client.SendHttpRequest();
wstring httpResponseHeader = client.GetResponseHeader();
wstring httpResponseContent = client.GetResponseContent();

Specifying the Proxy

Sometimes, we have to connect to the web through proxies. WinHttpClient connects to the web server directly and then uses the Internet Explorer setting to connect if it fails by default. You can also specify the proxy by calling function SetProxy.

Hide   Copy Code

WinHttpClient client(L"http://www.codeproject.com/");

// Set the proxy to 192.168.0.1 with port 8080.
client.SetProxy(L"192.168.0.1:8080");

client.SendHttpRequest();
wstring httpResponseHeader = client.GetResponseHeader();
wstring httpResponseContent = client.GetResponseContent();

Handling Cookies

A cookie (also tracking cookie, browser cookie, and HTTP cookie) is a small piece of text stored on a user‘s computer by a web browser. A cookie consists of one or more name-value pairs containing bits of information.

The cookie is sent as an HTTP header by a web server to a web browser and then sent back unchanged by the browser each time it accesses that server. A cookie can be used for authentication, session tracking (state maintenance), storing site preferences, shopping cart contents, the identifier for a server-based session, or anything else that can be accomplished through storing textual data (http://en.wikipedia.org/wiki/HTTP_cookie).

You can specify cookies to send by calling SetAdditionalRequestCookies and get the response cookies by calling GetResponseCookies.

Hide   Copy Code

WinHttpClient client(L"http://www.codeproject.com/");

// Set the cookies to send.
client.SetAdditionalRequestCookies(L"username=jack");

client.SendHttpRequest();

// Get the response cookies.
wstring httpResponseCookies = client.GetResponseCookies();

wstring httpResponseHeader = client.GetResponseHeader();
wstring httpResponseContent = client.GetResponseContent();

HTTPS

Hide   Copy Code

WinHttpClient client(L"https://www.google.com/");

// Accept any certificate while performing HTTPS request.
client.RequireValidSslCertificates(false);

client.SendHttpRequest();
wstring httpResponseHeader = client.GetResponseHeader();
wstring httpResponseContent = client.GetResponseContent();

Multiple Requests

Hide   Copy Code

WinHttpClient client(L"http://www.google.com/");

client.SendHttpRequest();
wstring httpResponseHeader = client.GetResponseHeader();
wstring httpResponseContent = client.GetResponseContent();

// Update the URL.
client.UpdateUrl(L"http://www.microsoft.com/");
client.SendHttpRequest();
httpResponseHeader = client.GetResponseHeader();
httpResponseContent = client.GetResponseContent();

A Complete Example

Codeproject.com needs logging in to download the files. This example logs in, gets the cookies, requests the source code (win_HTTP_wrapper/WinHttpClient_Src.zip) of my first CodeProject article, A Simple Windows HTTP Wrapper Using C++, and then saves the file to hard disk. This example includes cookies handling, post requests, request headers customization, etc.

Hide   Shrink    Copy Code

// 1. Get the initial cookie.
WinHttpClient getClient
	(L"http://www.codeproject.com/script/Membership/LogOn.aspx");
getClient.SetAdditionalRequestHeaders
	(L"Accept: image/gif, image/jpeg, image/pjpeg, image/pjpeg, ...");
if (!getClient.SendHttpRequest())
{
    return;
}

// 2. Post data to get the authentication cookie.
WinHttpClient postClient
	(L"http://www.codeproject.com/script/Membership/LogOn.aspx?rp=
	%2fscript%2fMembership%2fLogOn.aspx");

// Post data.
wstring username = L"YourCodeProjectUsername";
wstring password = L"YourPassword";
postClient.SetAdditionalRequestCookies(getClient.GetResponseCookies());
string data = "FormName=MenuBarForm&Email=";
data += (char *)_bstr_t(username.c_str());
data += "&Password=";
data += (char *)_bstr_t(password.c_str());
data += "&RememberMeCheck=1";
postClient.SetAdditionalDataToSend((BYTE *)data.c_str(), data.size());

// Post headers.
wstring headers = L"...Content-Length: %d\r\nProxy-Connection:
		Keep-Alive\r\nPragma: no-cache\r\n";
wchar_t szHeaders[MAX_PATH * 10] = L"";
swprintf_s(szHeaders, MAX_PATH * 10, headers.c_str(), data.size());
postClient.SetAdditionalRequestHeaders(szHeaders);
if (!postClient.SendHttpRequest(L"POST", true))
{
    return;
}

// 3. Finally get the zip file.
WinHttpClient downloadClient(L"win_HTTP_wrapper/WinHttpClient_Src.zip");
downloadClient.SetUserAgent(L"Mozilla/4.0
		(compatible; MSIE 8.0; Windows NT 5.1; ...)");

// Sending this cookie makes the server believe you have already logged in.
downloadClient.SetAdditionalRequestCookies(postClient.GetResponseCookies());
if (!downloadClient.SendHttpRequest())
{
    return;
}
downloadClient.SaveResponseToFile(L"C:\\WinHttpClient_Src.zip");

Points of Interest

  • Sometimes, it is a good idea to get a piece of new code working first and improve it later.
  • Reading the Hypertext Transfer Protocol (RFC 2616) will help a lot.
  • Use HTTP monitoring tools to help the development, such as HTTPAnalyzer or HTTPWatch.
  • It is fast and easy to use class _bstr_t to convert between wchar_t* and char*.

History

  • 2010-9-21 2 enhancements, thanks Scott Leckie
  • 2010-4-29 2 Bugs fixed, thanks Wong Shao Voon
  • 2009-9 Fully featured version
  • 2008-7 Initial version
时间: 2024-10-10 14:39:11

Http Wrapper vs2008工程的相关文章

VS2008 工程中部分文件不参与编译 从生成中排除【Worldsing笔记】

Visual Studio 2008 .VS2008.VC2008工程源文件配置.编译配置 ? 有时编写代码时,往往存在这样的需求(或是希望有这样的功能):一个工程经过不共同的配置实现不同的版本或是功能,比如做开发包的Dome,一个库文件, 有多个API接口,以lib文件给用户提供时,我们需要提供文档和Demo,你可以一个Demo建立一个工程,但是,像VS2008这样的高级开发工具应该有解决 办法的,关键是你不知道怎么用,在VS2008环境下有这样几种解决办法: ? 建立一个工作区,在工作区里建

VS2010编译VS2008工程时,LINK : fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt

1.问题 电脑上同时安装了VS2008,VS2010,使用VS2010编译VS2008建立的工程,或者,VS2010创建新的工程.编译时,出现以下链接错误: LINK : fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt ? 2.修改 安装Visual Studio 2010 Service Pack 1补丁. http://www.microsoft.com/en-us/downloa

VS2008 工程只生成dll不生成lib的解决方案

http://topic.csdn.net/u/20081216/22/b12d1450-7585-4c9f-867a-7c181737c328.html 问题:vs2008版本的,不知道为什么只生成dll,不生成lib文件了. 解决方案: 在工程上右键 -> 添加 -> 新建项 -> 选"模块定义文件(.def)" -> 随便输入个名字 -> 添加现在编译就可生成.lib 文件了,然后把添加的文件删除,以后都没问题了.如果上边的操作是添加现有项,不能产生

emWin5.24 VS2008模拟LCD12864 stm32 RTX移植 【worldsing笔记】

? emWin for 12864 并口移植 源代码下载:RTX_emWin5.24_Keil_VS2008-20141122.zip ? 硬件环境: CPU: stm32f103ve LCD:st7920控制器 12864 并口 ? 软件环境: Keil MDK4.74 VS2008 emWin5.24 ? 使用rtx操作系统 ? ? 1.实现emWin5.24在keil 和vs2008同一代码的工程,vs2008目录实现在FMC的官方模拟器上的模拟,Keil目录实现在stm32f103ve

在VS2008环境下编写C语言DLL,并在C++和C#项目下调用 (转载)

1.编写DLL a)文件--打开--新建项目--Win32,右侧Win32项目,填写好项目名称,点击“下一步”, 应用程序类型选择:“DLL(D)”,附加选项:空项目(E),然后完成. b)编写头文件(edrlib.h): #ifdef __cplusplus   #define EXPORT extern "C" __declspec (dllexport)   #else   #define EXPORT __declspec (dllexport)   #endif      E

CUDA从入门到精通

CUDA从入门到精通(零):写在前面 在老板的要求下,本博主从2012年上高性能计算课程开始接触CUDA编程,随后将该技术应用到了实际项目中,使处理程序加速超过1K,可见基于图形显示器的并行计算对于追求速度的应用来说无疑是一个理想的选择.还有不到一年毕业,怕是毕业后这些技术也就随毕业而去,准备这个暑假开辟一个CUDA专栏,从入门到精通,步步为营,顺便分享设计的一些经验教训,希望能给学习CUDA的童鞋提供一定指导.个人能力所及,错误难免,欢迎讨论. PS:申请专栏好像需要先发原创帖超过15篇...

OpenCV学习:OpenCV源码编译(vc9)

安装后的OpenCV程序下的build文件夹中,只找到了vc10.vc11和vc12三种编译版本的dll和lib文件,需要VS2010及以上的IDE版本,而没有我们常用的VS2008版本. 于是,需要的小伙伴们可以自己动手,丰衣足食! 1). 安装CMake cmake-2.8.8-win32-x86.exe (http://www.cmake.org/cmake/resources/software.html) 百度云盘:http://pan.baidu.com/s/1dEYbx77  密码:

c++心得

c++学习了之后,让我对c++产生了很多的疑问,首先c++当中的虚函数,知道了虚函数表在内存中存在的地址位于类实例首地址中.在学习了java 连接数据库之后,悠然我产生了一个想法就是能不能通过c++来连接数据库呢,于是我就在网上查找了相关的代码并接了数据库.    (1)安装MySql  Server在本机上,安装过程就不细说了.    (2)解压Mysql++后,一般通常使用的是VS2008工程来uppdate.    (3)接下来就是编写我们的代码来操作数据库了,当然了,在这之前,你的mys

C Run-Time Error R6034问题的解决

1.问题描述 这两天一直在用vs2008编写一个小项目,需要在c++代码中通过命令行的方式调用cl.exe和link.exe,也就是给编译器cl和链接器link传递参数,然后编译链接生成可执行文件exe.最终生成的result.exe运行时老出现Runtime Error R6034 An application has made an attempt to load the C runtime library incorrectly.的错误,围绕这个问题,我查了两天的资料,最后终于解决了..