c post html,http_post.c

/* http_post_simple - do a POST to an HTTP URL and return the values

Copyright GPL 2003 by Mike Chirico

Updated: Sun Jun 13 13:53:14 EDT 2004

A few things to note with this example:

.. note the \r\n .. it needs a carrage return line feed

"POST /test.php HTTP/1.0\r\n"

"Host: souptonuts.sourceforge.net\r\n"

souptonuts.sourceforge.net ip address is 66.35.250.209

but use the dns name "souptonuts.sourceforge.net"

A note on Content-length

"Content-length: 36\r\n\r\n"

->"mode=login&user=test&password=test\r\n"

36 is the length of the string "mode=login&user=test&password=test\r\n"

If the string is changed, then length must be adjusted.

Reference:

http://souptonuts.sourceforge.net/chirico/test.php

http://souptonuts.sourceforge.net/code/test.php.html

Download:

http://prdownloads.sourceforge.net/cpearls/spider.tar.gz?download

*/

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#define SA struct sockaddr

#define MAXLINE 4096

#define MAXSUB 200

#define LISTENQ 1024

extern int h_errno;

ssize_t process_http(int sockfd, char *host, char *page, char *poststr)

{

char sendline[MAXLINE + 1], recvline[MAXLINE + 1];

ssize_t n;

snprintf(sendline, MAXSUB,

"POST %s HTTP/1.0\r\n"

"Host: %s\r\n"

"Content-type: application/x-www-form-urlencoded\r\n"

"Content-length: %d\r\n\r\n"

"%s", page, host, strlen(poststr), poststr);

write(sockfd, sendline, strlen(sendline));

while ((n = read(sockfd, recvline, MAXLINE)) > 0) {

recvline[n] = '\0';

printf("%s", recvline);

}

return n;

}

int main(void)

{

int sockfd;

struct sockaddr_in servaddr;

char **pptr;

//********** You can change. Puy any values here *******

char *hname = "souptonuts.sourceforge.net";

char *page = "/chirico/test.php";

char *poststr = "mode=login&user=test&password=test\r\n";

//*******************************************************

char str[50];

struct hostent *hptr;

if ((hptr = gethostbyname(hname)) == NULL) {

fprintf(stderr, " gethostbyname error for host: %s: %s",

hname, hstrerror(h_errno));

exit(1);

}

printf("hostname: %s\n", hptr->h_name);

if (hptr->h_addrtype == AF_INET

&& (pptr = hptr->h_addr_list) != NULL) {

printf("address: %s\n",

inet_ntop(hptr->h_addrtype, *pptr, str,

sizeof(str)));

} else {

fprintf(stderr, "Error call inet_ntop \n");

}

sockfd = socket(AF_INET, SOCK_STREAM, 0);

bzero(&servaddr, sizeof(servaddr));

servaddr.sin_family = AF_INET;

servaddr.sin_port = htons(80);

inet_pton(AF_INET, str, &servaddr.sin_addr);

connect(sockfd, (SA *) & servaddr, sizeof(servaddr));

process_http(sockfd, hname, page, poststr);

close(sockfd);

exit(0);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值