c语言http的http_get和http_post的实现

http.c

#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>

#include "http.h"

#define BUFFER_SIZE 1024
#define HTTP_POST "POST /%s HTTP/1.1\r\nHOST: %s:%d\r\nAccept: */*\r\n"\
	"Content-Type:application/x-www-form-urlencoded\r\nContent-Length:\
	%d\r\n\r\n%s"

#define HTTP_GET "GET /%s HTTP/1.1\r\nHOST: %s:%d\r\nAccept: */*\r\n\r\n"

static int http_tcpclient_create(const char *host, int port)
{
	struct hostent *he;
	struct sockaddr_in server_addr; 
	int socket_fd;

	if ((he = gethostbyname(host)) == NULL) {
		return -1;
	}

	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(port);
	server_addr.sin_addr = *((struct in_addr *)he->h_addr);

	if ((socket_fd = socket(AF_INET,SOCK_STREAM,0)) == (-1)) {
		return -1;
	}

	if (connect(socket_fd,
		(struct sockaddr *)&server_addr,
		sizeof(struct sockaddr)) == -1) {
		return -1;
	}

	return socket_fd;
}

static void http_tcpclient_close(int socket)
{
	close(socket);
}

static int http_parse_url(const char *url, char *host, char *file, int *port)
{
	char *ptr1, *ptr2;
	int len = 0;
	if (!url || !host || !file || !port) {
		return -1;
	}

	ptr1 = (char *)url;

	if (!strncmp(ptr1, "http://", strlen("http://"))) {
		ptr1 += strlen("http://");
	} else {
		return -1;
	}

	ptr2 = strchr(ptr1, '/');
	if (ptr2) {
		len = strlen(ptr1) - strlen(ptr2);
		memcpy(host, ptr1, len);
		host[len] = '\0';
		if (*(ptr2 + 1)) {
			memcpy(file,ptr2 + 1,strlen(ptr2) - 1 );
			file[strlen(ptr2) - 1] = '\0';
		}
	} else {
		memcpy(host,ptr1,strlen(ptr1));
		host[strlen(ptr1)] = '\0';
	}
	ptr1 = strchr(host,':');
	if (ptr1) {
		*ptr1++ = '\0';
		*port = atoi(ptr1);
	} else {
		*port = MY_HTTP_DEFAULT_PORT;
	}

	return 0;
}

static int http_tcpclient_recv(int socket, char *lpbuff)
{
	int recvnum = 0;

	recvnum = recv(socket, lpbuff, BUFFER_SIZE*4, 0);

	return recvnum;
}

static int http_tcpclient_send(int socket, char *buff, int size)
{
	int sent=0, tmpres=0;

	while (sent < size) {
		tmpres = send(socket, buff+sent, size-sent, 0);
		if(tmpres == -1){
			return -1;
		}
		sent += tmpres;
	}
	return sent;
}

static char *http_parse_result(const char*lpbuf)
{
	char *ptmp = NULL; 
	char *response = NULL;
	ptmp = (char*)strstr(lpbuf, "HTTP/1.1");
	if (!ptmp) {
		printf("http/1.1 not faind\n");
		return NULL;
	}
	if (atoi(ptmp + 9) != 200){
		printf("result:\n%s\n", lpbuf);
		return NULL;
	}

	ptmp = (char *)strstr(lpbuf, "\r\n\r\n");
	if (!ptmp) {
		printf("ptmp is NULL\n");
		return NULL;
	}
	response = (char *)malloc(strlen(ptmp) + 1);
	if (!response) {
		printf("malloc failed \n");
		return NULL;
	}
	strcpy(response, ptmp+4);
	return response;
}

char *http_post(const char *url, const char *post_str)
{

	int socket_fd = -1;
	char lpbuf[BUFFER_SIZE*4] = {'\0'};
	char host_addr[BUFFER_SIZE] = {'\0'};
	char file[BUFFER_SIZE] = {'\0'};
	int port = 0;

	if (!url || !post_str) {
		printf("failed!\n");
		return NULL;
	}

	if (http_parse_url(url, host_addr, file, &port)) {
		printf("http_parse_url failed!\n");
		return NULL;
	}

	socket_fd = http_tcpclient_create(host_addr, port);
	if (socket_fd < 0) {
		printf("http_tcpclient_create failed\n");
		return NULL;
	}

	sprintf(lpbuf,
		HTTP_POST,
		file,
		host_addr,
		port,
		(int)strlen(post_str),
		post_str);

	if (http_tcpclient_send(socket_fd, lpbuf, strlen(lpbuf)) < 0) {
		printf("http_tcpclient_send failed..\n");
		return NULL;
	}

	/*it's time to recv from server*/
	if (http_tcpclient_recv(socket_fd,lpbuf) <= 0) {
		printf("http_tcpclient_recv failed\n");
		return NULL;
	}

	http_tcpclient_close(socket_fd);

	return http_parse_result(lpbuf);
}

char *http_get(const char *url)
{
	int socket_fd = -1;
	char lpbuf[BUFFER_SIZE*4] = {'\0'};
	char host_addr[BUFFER_SIZE] = {'\0'};
	char file[BUFFER_SIZE] = {'\0'};
	int port = 0;

	if (!url) {
		printf("failed!\n");
		return NULL;
	}

	if (http_parse_url(url,host_addr,file,&port)) {
		printf("http_parse_url failed!\n");
		return NULL;
	}

	socket_fd = http_tcpclient_create(host_addr,port);
	if (socket_fd < 0) {
		printf("http_tcpclient_create failed\n");
		return NULL;
	}

	sprintf(lpbuf,HTTP_GET,file,host_addr,port);

	if (http_tcpclient_send(socket_fd,lpbuf,strlen(lpbuf)) < 0) {
		printf("http_tcpclient_send failed..\n");
		return NULL;
	}

	if (http_tcpclient_recv(socket_fd,lpbuf) <= 0) {
		printf("http_tcpclient_recv failed\n");
		return NULL;
	}
	http_tcpclient_close(socket_fd);

	return http_parse_result(lpbuf);
}

http.h

#ifndef _MY_HTTP_H
#define _MY_HTTP_H
 
#define MY_HTTP_DEFAULT_PORT 80

char *http_get(const char *url);
char *http_post(const char *url,const char * post_str);
 
#endif

 

  • 1
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
C语言中,可以使用一些库来执行HTTP的GET和POST请求,并下载文件。在这里,我们将使用libcurl库来完成这些操作。 首先,我们需要在代码中引入libcurl库的头文件。 ```c #include <stdio.h> #include <curl/curl.h> ``` 然后,我们可以定义一个回调函数,用于处理下载的数据。 ```c size_t write_callback(void* ptr, size_t size, size_t nmemb, FILE* stream) { return fwrite(ptr, size, nmemb, stream); } ``` 接下来,我们可以编写一个函数来执行HTTP的GET请求,并将返回的数据保存到文件中。 ```c void http_get(const char* url, const char* file_path) { FILE* file = fopen(file_path, "wb"); if (file == NULL) { printf("无法打开文件!\n"); return; } CURL* curl = curl_easy_init(); if (curl) { curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, file); CURLcode res = curl_easy_perform(curl); if (res != CURLE_OK) { printf("请求失败:%s\n", curl_easy_strerror(res)); } curl_easy_cleanup(curl); } fclose(file); } ``` 最后,我们可以编写一个函数来执行HTTPPOST请求,并将返回的数据保存到文件中。 ```c void http_post(const char* url, const char* post_data, const char* file_path) { FILE* file = fopen(file_path, "wb"); if (file == NULL) { printf("无法打开文件!\n"); return; } CURL* curl = curl_easy_init(); if (curl) { curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, file); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post_data); CURLcode res = curl_easy_perform(curl); if (res != CURLE_OK) { printf("请求失败:%s\n", curl_easy_strerror(res)); } curl_easy_cleanup(curl); } fclose(file); } ``` 通过使用以上两个函数,我们可以下载一个文件到指定的路径。例如,假设我们要下载一个名为"test.txt"的文件,可以使用以下代码: ```c http_get("http://example.com/test.txt", "test.txt"); ``` 或者,如果我们需要通过POST请求下载文件,可以使用以下代码: ```c const char* post_data = "param1=value1&param2=value2"; http_post("http://example.com/download", post_data, "test.txt"); ``` 以上就是使用C语言执行HTTP的GET和POST请求,并下载文件的示例代码。
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值