C++使用POST方法向网页提交数据-----C++发送HTTP数据获取Google天气预报
例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 = ;
DWORD dwRet = ; 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[];
pEx->GetErrorMessage(pszError, ); 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(,),&WsaData))
{
printf("The socket failed");
return false;
}
#endif SOCKET sockeId;
SOCKADDR_IN addr; if (- == (sockeId = socket(AF_INET, SOCK_STREAM, )))
{
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(); //> request_url
/* www.it165.net
* 分离url中的主机地址和相对路径
*/
char *phost = ;
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), ))
{
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, ) > )
{
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 -;
}
printf( "Whether have been writtend to file whether.xml\n" ); system( "pause");
return ;
}
关于内存释放,自己封装了一个变参形式的(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;
}
}
C++使用POST方法向网页提交数据-----C++发送HTTP数据获取Google天气预报的更多相关文章
- Python开发实战教程(8)-向网页提交获取数据
来这里找志同道合的小伙伴!↑↑↑ Python应用现在如火如荼,应用范围很广.因其效率高开发迅速的优势,快速进入编程语言排行榜前几名.本系列文章致力于可以全面系统的介绍Python语言开发知识和相关知 ...
- Android之使用HTTP协议的Get/Post方式向服务器提交数据
1.Get方式 方法:通过拼接url在url后添加相应的数据,如:http://172.22.35.112:8080/videonews/GetInfoServlet?title=霍比特人&t ...
- Silverlight实例教程 - Validation用户提交数据验证捕获(转载)
Silverlight 4 Validation验证实例系列 Silverlight实例教程 - Validation数据验证开篇 Silverlight实例教程 - Validation数据验证基础 ...
- C#中UDP数据的发送、接收
Visual C# UDP数据的发送、接收包使用的主要类及其用法: 用Visual C# UDP协议的实现,最为常用,也是最为关键的类就是UdpClient,UdpClient位于命名空间System ...
- 在php中分别使用curl的post提交数据的方法和get获取网页数据的方法
在php中分别使用curl的post提交数据的方法和get获取网页数据的方法整理分享一下额,具体代码如下: (1)使用php curl获取网页数据的方法: $ch=curl_init(); //设置选 ...
- Django—Form两种保留用户提交数据的方法
用户在网页上进行表单填写时,有可能出现某项填写错误.一般情况下,用户在未发觉错误的情况下点击提交,则此表单的内容会清空,用户不得不再重新填写,这样的用户体验是及其糟糕的. 在此,我们有2种方法将用户的 ...
- ASP模拟POST请求异步提交数据的方法
这篇文章主要介绍了ASP模拟POST请求异步提交数据的方法,本文使用MSXML2.SERVERXMLHTTP.3.0实现POST请求,需要的朋友可以参考下 有时需要获取远程网站的某些信息,而服务器又限 ...
- 2016 系统设计第一期 (档案一)jQuery ajax serialize()方法form提交数据
jQuery ajax serialize()方法form提交数据,有个很奇怪的问题,好像不能取到隐藏控件的值. //点击提交按钮保存数据 $('#btn_submitUser').click(fun ...
- angular的$http.post()提交数据到Java后台接收不到参数值问题的解决方法
本文地址:http://www.cnblogs.com/jying/p/6733408.html 转载请注明出处: 写此文的背景:在工作学习使用angular的$http.post()提交数据时, ...
随机推荐
- 利用mycat实现mysql数据库读写分离
1.这里是在mysql主从复制实现的基础上,利用mycat做读写分离,架构图如下: 2.Demo 2.1 在mysql master上创建数据库创建db1 2.2 在数据库db1创建表student ...
- 如何查看连接mysql的ip地址
select SUBSTRING_INDEX(host,':',1) as ip , count(*) from information_schema.processlist group by ip;
- bfs A strange lift
题目:http://acm.hdu.edu.cn/showproblem.php?pid=1548 There is a strange lift.The lift can stop can at e ...
- python 练习 17
#!/usr/bin/python # -*- coding: UTF-8 -*- f1 = 1 f2 = 1 for i in range(1,21): print '%12d %12d' % (f ...
- HTML5自学笔记[ 14 ]canvas绘图基础2
canvas绘制路径不仅可以绘制直线和多边形,还提供了绘制曲线的方法,利用这些方法可以画出多种曲线效果. 方法1:arc(x,y,r,起始弧度,结束弧度,绘制方向);其中(x,y)为圆心坐标,r为半径 ...
- javascript常用函数(1):jquery操作select 基本操作
$(this).children('option:selected').val();//这就是selected的值 $("#charCity").empty();//内容清空: j ...
- STL中vector的用法
vector是标准模板库的一种容器,是可存放各种类型的动态数组. #include<iostream> #include<vector> using namespace std ...
- hdu---(3555)Bomb(数位dp(入门))
Bomb Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/65536 K (Java/Others)Total Submi ...
- HTML5标签学习之~~~
<article> 标签 article 字面意思为“文章”.在web页面中表现为独立的内容,如一篇新闻,一篇评论,一段名言,一段联系方式.这其中包括两方面,一为整个页面的主旨内容,另外就 ...
- 分形树Fractal tree介绍——具体如何结合TokuDB还没有太懂,先记住其和LSM都是一样的适合写密集
在目前的Mysql数据库中,使用最广泛的是innodb存储引擎.innodb确实是个很不错的存储引擎,就连高性能Mysql里都说了,如果不是有什么很特别的要求,innodb就是最好的选择.当然,这偏文 ...