例1:C++使用POST方法向網頁提交數據 轉自:http://www.it165.net/pro/html/201208/3534.html
在C++中可以使用POST方法向網頁中提交數據,這樣就可以向類似論壇這樣的網站注入垃圾帖子了。我的博客常常有海量的垃圾評論,大為惱火。
為了不給其他人惹麻煩,就在本機測試。
#include <iostream> #include <string> #include <afxinet.h> //定義了MFC CInternetSession類等 bool PostHttpPage(const std::string& hostName, const std::string& pathName, const std::string& postData) { using namespace std; CInternetSession session("your app agent name"); try { INTERNET_PORT nPort = 80; DWORD dwRet = 0; CHttpConnection* pServer = session.GetHttpConnection( hostName.c_str(),nPort); CHttpFile* pFile = pServer->OpenRequest(CHttpConnection:: HTTP_VERB_POST,pathName.c_str()); CString strHeaders = "Content-Type: application/x-www-form- urlencoded"; //請求頭 //開始發送請求 pFile->SendRequest(strHeaders,(LPVOID)postData.c_str(), postData.size()); pFile->QueryInfoStatusCode(dwRet); if (dwRet == HTTP_STATUS_OK) { CString result, newline; while(pFile->ReadString(newline)) {//循環讀取每行內容 result += newline+"\r\n"; } std::cout<<result<<std::endl;//顯示返回內容 } else { return false; } delete pFile; delete pServer; } catch (CInternetException* pEx) { //catch errors from WinInet TCHAR pszError[200]; pEx->GetErrorMessage(pszError, 200); std::cout<<pszError<<std::endl;//顯示異常信息 return false; } session.Close(); return true; } int main(void) { //向本機Web目錄下面的welcome.php頁面發送發送 PostHttpPage("localhost","welcome.php","name=rain&age=21"); }
在工程設計中,要選擇-Use mfc in a shard dll 選項。
在本機Web目錄下面(就是Apache服務器配置文件中Directory配置的路徑 ),存有welcome.php文件,當該文件收到post請求時,將請求的數據寫入到文件中:
<?php $file = fopen("./test.txt","w"); fwrite($file,$_POST["name"]); fwrite($file,$_POST["age"]); fclose($file); ?>
運行C++程序,在Web目錄下面就會生成一個test.txt文本,文本的內容為rain21.
例2:C++發送HTTP數據獲取Google天氣預報 轉自:http://www.it165.net/pro/html/201208/3534.html
工作一個星期了,基本都在看別人代碼。現在主要看的是Http部分的,不斷和服務器交互,不斷得到反饋信息或者提交信息。諸如此類,因此為了加深C對Http的處理,還是稍微練習下或者說了解和實驗下,俗話說“好記性不如爛筆頭”,厲害的人都是靠學習來的。
在Windows下利用C語言進行http請求,想google天氣API發送請求獲取數據並保存!以下是工程文件:
各個文件代碼:
downdata.h
#ifndef DOWNDATA_H_INCLUDED #define DOWNDATA_H_INCLUDED #define BUFFSIZE_H 1024 #ifdef __cpluscplus extern "C" { #endif /** * @brief 向網絡請求資源,返回值存儲到當前目錄的臨時文件whether.txt中. * @param pUrl - 請求的URL. * @return if get data return true, else if get nothing return false. */ bool WEBQuest(const char * pUrl); #ifdef __cpluscplus } #endif #endif // DOWNDATA_H_INCLUDED
downdata.cpp
#include <stdio.h> #include <stdlib.h> #include <string.h> //#include "windows.h" #include "winsock2.h" #include "downdata.h" #include "freeptr.h" #pragma comment(lib, "ws2_32.lib") //在某些編譯器下,需要添加編譯參數到工程設置中,比如CodeBlocks(這樣,這行就不需要了). //Code::blocks 中新建一個工程, 然后右擊工程 //選擇 build options //選擇Linker setting //在 Other linker options 中添加: -lwsock32 /** * @brief 為了加深http的理解和數據相關的操作,實現之. */ bool WEBQuest(const char * pUrl) { #if 1 //no this declaration, socket create failed. WSADATA WsaData; if (WSAStartup(MAKEWORD(2,2),&WsaData)) { printf("The socket failed"); return false; } #endif SOCKET sockeId; SOCKADDR_IN addr; if (-1 == (sockeId = socket(AF_INET, SOCK_STREAM, 0))) { printf("socket create failed\n"); return false; } //> dest_addr addr.sin_addr.S_un.S_addr = inet_addr("74.125.71.105"); //> googleIP,可以用IP地址查詢得到 addr.sin_family = AF_INET; addr.sin_port = htons(80); //> request_url /* www.it165.net * 分離url中的主機地址和相對路徑 */ char *phost = 0; char * myurl = (char * ) malloc (BUFFSIZE_H * sizeof(char)); char * host = (char * ) malloc (BUFFSIZE_H * sizeof(char)); char * GET = (char * ) malloc (BUFFSIZE_H * sizeof(char)); char * head =(char * ) malloc(BUFFSIZE_H * sizeof(char)); memset(myurl, '\0', BUFFSIZE_H); memset(host, '\0', BUFFSIZE_H); memset(GET, '\0', BUFFSIZE_H); memset(head, '\0', BUFFSIZE_H); //> pUrl - www.google.com/ig/api?hl=zh_cn&weather=beijing //> www.google.com - &host //> /ig/api?hl=zh_cn&weather=beijing - &GET strcpy(myurl, pUrl); for (phost = myurl; *phost != '/' && *phost != '\0'; ++phost); if ( (int)(phost - myurl) == strlen(myurl) ) strcpy(GET, "/"); else strcpy(GET, phost); *phost = '\0'; //> 相當於在www.google.com/的/位置替換為'\0'. strcpy(host, myurl);//> 在www.google.com/的/位置為'\0',因此www.google.com被拷貝到&host. printf("%s\n%s\n", host, GET); /* * 組織發送到web服務器的信息 * 為何要發送下面的信息connect請參考HTTP協議的約定 */ strcat(head, "GET "); strcat(head, GET); strcat(head, " HTTP/1.1\r\n"); strcat(head, "host: "); strcat(head, host); strcat(head, "\r\nConnection: Close\r\n\r\n"); printf(head); if (SOCKET_ERROR == connect(sockeId, (SOCKADDR * )&addr, sizeof(addr))) { printf("connect failed!\n"); closesocket(sockeId); WSACleanup(); #if 0 free(myurl); free(host); free(GET); free(head); myurl = NULL; host = NULL; GET = NULL; head = NULL; #endif freeCharPtr(&myurl, &host, &GET, &head, NULL); return false; } if (SOCKET_ERROR == send(sockeId, head, strlen(head), 0)) { printf("send &header error!\n"); closesocket(sockeId); WSACleanup(); #if 0 free(myurl); free(host); free(GET); free(head); myurl = NULL; host = NULL; GET = NULL; head = NULL; #endif freeCharPtr(&myurl, &host, &GET, &head, NULL); return false; } memset(head, '\0', BUFFSIZE_H); FILE *fp; fp = fopen("whether.xml", "w+"); if (NULL == fp) { printf("whether file create failed!\n"); closesocket(sockeId); WSACleanup(); #if 0 free(myurl); free(host); free(GET); free(head); myurl = NULL; host = NULL; GET = NULL; head = NULL; #endif freeCharPtr(&myurl, &host, &GET, &head, NULL); return false; } while (recv(sockeId, head, BUFFSIZE_H, 0) > 0) { fputs(head, fp); memset(head, '\0', BUFFSIZE_H); } #if 0 free(myurl); free(host); free(GET); free(head); myurl = NULL; host = NULL; GET = NULL; head = NULL; #endif freeCharPtr(&myurl, &host, &GET, &head, NULL); closesocket(sockeId); WSACleanup(); return true; }
main.cpp
#include <iostream> //> system #include <stdio.h> #include "downdata.h" using namespace std; int main(void ) { if (!WEBQuest("www.google.com/ig/api?hl=zh_cn&weather=beijing" )) { return -1; } printf( "Whether have been writtend to file whether.xml\n" ); system( "pause"); return 0; }
關於內存釋放,自己封裝了一個變參形式的(char *參數)釋放函數
freeptr.h
#ifndef FREEPTR_H #define FREEPTR_H #ifdef __cpluscplus extern "C" { #endif void freeCharPtr(char ** ch, ...); #ifdef __cpluscplus } #endif #endif
freeptr.cpp
#include <stdlib.h> #include <stdarg.h> #include "freeptr.h" void freeCharPtr(char ** ch, ...) { va_list ap; char ** p; va_start(ap, ch); free(*ch); *ch = NULL; while (p = va_arg(ap, char ** )) { free(*p); *p = NULL; } }