libcurl get post http
一、 概念
1. 為什么要使用libcurl
1) 作為http的客戶端,可以直接用socket連接服務器,然后對到的數據進行http解析,但要分析協議頭,實現代理…這樣太麻煩了。
2) libcurl是一個開源的客戶端url傳輸庫,支持 FTP,FTPS,TFTP,HTTP,HTTPS,GOPHER,TELNET,DICT,FILE和LDAP,支持 Windows,Unix,Linux等平臺,簡單易用,且庫文件占用空間不到200K
2. get和post方式
客戶端在http連接時向服務提交數據的方式分為get和post兩種
1) Get方式將所要傳輸的數據附在網址后面,然后一起送達服務器,它的優點是效率比較高;缺點是安全性差、數據不超過1024個字符、必須是7位的ASCII編碼;查詢時經常用此方法。
2) Post通過Http post處理發送數據,它的優點是安全性較強、支持數據量大、支持字符多;缺點是效率相對低;編輯修改時多使用此方法。
3. cookie與session
1) cookie
cookie是發送到客戶瀏覽器的文本串句柄,并保存在客戶機硬盤上,可以用來在某個Web站點會話之間持久地保持數據。cookie在客戶端。
2) session
session是訪問者從到達某個特定主頁到離開為止的那段時間。每一訪問者都會單獨獲得一個session,實現站點多個用戶之間在所有頁面中共享信息。session在服務器上。
3) libcurl中使用cookie
保存cookie, 使之后的鏈接與此鏈接使用相同的cookie
a) 在關閉鏈接的時候把cookie寫入指定的文件
curl_easy_setopt(curl, CURLOPT_COOKIEJAR, “/tmp/cookie.txt”);
b) 取用現在有的cookie,而不重新得到cookie
curl_easy_setopt(curl, CURLOPT_COOKIEFILE, “/tmp/cookie.txt”);
b) http與https的區別
1) Http是明文發送,任何人都可以攔截并讀取內容
2) Https是加密傳輸協議,用它傳輸的內容都是加密過的,https是http的擴展,其安全基礎是SSL協議
c) base64編碼
1) 為什么要使用base64編碼
如果要傳一段包含特殊字符比較多的數據,直接上傳就需要處理轉意符之類的很多問題,用base64編碼,它可以把數據轉成可讀的字串,base64由a-z, A-Z, +/總計64個字符組成。
2) 傳送base64編碼的注意事項
由于base64的組成部分有加號,而加號是url中的轉意字符,所以無論是get方式還是post,傳到服務器的過程中,都會把加號轉成空格,所以在傳base64之前需要把base64編碼后的加號替換成”+”,這樣就可以正常發送了。
二、 例程
d) 代碼
#include <stdio.h>
#include <curl/curl.h>
bool getUrl(char *filename)
{
CURL *curl;
CURLcode res;
FILE *fp;
if ((fp = fopen(filename, “w”)) == NULL) // 返回結果用文件存儲
return false;
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, “Accept: Agent-007″);
curl = curl_easy_init(); // 初始化
if (curl)
{
curl_easy_setopt(curl, CURLOPT_PROXY, “10.99.60.201:8080″);// 代理
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);// 改協議頭
curl_easy_setopt(curl, CURLOPT_URL, “http://www.google.com/search?hl=en&q=xieyan0811&btnG=Google+Search&aq=f&oq=xieyan081″);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
res = curl_easy_perform(curl); // 執行
curl_slist_free_all(headers);
curl_easy_cleanup(curl);
}
fclose(fp);
return true;
}
bool postUrl(char *filename)
{
CURL *curl;
CURLcode res;
FILE *fp;
if ((fp = fopen(filename, “w”)) == NULL)
return false;
curl = curl_easy_init();
if (curl)
{
curl_easy_setopt(curl, CURLOPT_COOKIEFILE, “/tmp/cookie.txt”); // 指定cookie文件
// curl_easy_setopt(curl, CURLOPT_COOKIEJAR, “/tmp/cookie.txt”);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, “&logintype=uid&u=xieyan&psw=xxx86″); // 指定post內容
curl_easy_setopt(curl, CURLOPT_PROXY, “10.99.60.201:8080″);
curl_easy_setopt(curl, CURLOPT_URL, “http://mail.sina.com.cn/cgi-bin/login.cgi”); // 指定url
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
}
fclose(fp);
return true;
}
int main(void)
{
getUrl(“/tmp/get.html”);
postUrl(“/tmp/post.html”);
}
RFID管理系統集成商 RFID中間件 條碼系統中間層 物聯網軟件集成