首先我们创建一个php页面:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<form action="#" method="post">
<input name="pass" type="text"></input>
<input name="submit" type="submit" value="Login"></input>
</form>
<?php
echo "Refer : " . $_SERVER['HTTP_REFERER'] . "<br>";
if(isset($_POST['pass']))
{
echo "Login successfully via Password <br> pass = " . $_POST['pass'] . "<br>";
setcookie("pass", "password");
}
else if(isset($_COOKIE['pass']))
{
echo "Login successfully via COOKIE <br> pass = " . $_COOKIE['pass'] . "<br>";
}
else
{
echo "Please login <br>";
}
?>
这是一个简单的登录页面,可以通过输入密码登陆,也可以通过cookie登陆。
我们将通过这个页面示范C语言通过libcurl库进行设置http请求头、post、cookie的操作。
C代码:
#include "stdafx.h"
#include "curl\curl.h"
size_t function( void *ptr, size_t size, size_t nmemb, void *stream)
{
printf("%s\n", (char*)ptr);
return 0;
}
int _tmain(int argc, TCHAR *argv[])
{
CURL *curl;
int i = 100;
struct curl_slist *cookies = NULL;
struct curl_slist *cookie = NULL;
struct curl_slist *headers = NULL;
curl = curl_easy_init();
headers = curl_slist_append(headers,"POST /VSCurlTest.php HTTP/1.1");
headers = curl_slist_append(headers,"Host:127.0.0.1");
headers = curl_slist_append(headers,"Connection: keep-alive");
headers = curl_slist_append(headers,"User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.2141.400 QQBrowser/9.5.10219.400");
headers = curl_slist_append(headers,"Cache-Control: max-age=0");
headers = curl_slist_append(headers,"Content-Type: application/x-www-form-urlencoded");
headers = curl_slist_append(headers,"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
headers = curl_slist_append(headers,"Referer:http://www.baidu.com");
headers = curl_slist_append(headers,"Accept-Encoding: gzip, deflate");
headers = curl_slist_append(headers,"Accept-Language: zh-CN,zh;q=0.8");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_COOKIEFILE,"");
curl_easy_setopt(curl, CURLOPT_COOKIEJAR, "cookie_open.txt");
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_URL, "http://127.0.0.1/VSCurlTest.php");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, function);
curl_easy_setopt(curl, CURLOPT_POST, 1);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "pass=23333&submit=%CC%E1%BD%BB");
curl_easy_setopt(curl, CURLOPT_COOKIE, "olfsk=olfsk7257964002188215; hblid=nR2Zo2hcfSVtItpT3m39N804DHbNAfAp; pass=adadad");
curl_easy_perform(curl);
curl_easy_getinfo(curl, CURLINFO_COOKIELIST, &cookies);
cookie = cookies;
while(cookie)
{
printf("%s\n", cookie->data);
cookie = cookie->next;
}
curl_slist_free_all(headers);
curl_slist_free_all(cookies);
curl_easy_cleanup(curl);
getchar();
return 0;
}
通过注释这个例子的某些curl_easy_setopt调用,观察输出信息,大概也能理解libcurl的使用了。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)