C语言 HTTP发送post和get请求

安装curl环境:

apt install curl
apt-get install libcurl4-openssl-dev

使用C语言来做HTTP协议,然后发送post和get请求,这里为post请求的代码,如下:

#include 
#include 
#include 
#include 
#include "MyJson.h"
 
#define POSTURL    "127.0.0.1:8080/VIID/System/Register"
#define POSTFIELDS "{\"hardware_id\":\"12345678\",\"gw_ip\":\"111.172.35.4\",\"gw_mac\":\"0C-9D-92-15-4C-02\",\"game_id\":\"223\"}"

int main(int argc,char *argv[])
{
	CURL *curl;
	CURLcode res;

	struct curl_slist *http_header = NULL;

	curl = curl_easy_init();
	if (!curl)
	{
		fprintf(stderr,"curl init failed\n");
		return -1;
	}
 
        curl_easy_setopt(curl,CURLOPT_URL,POSTURL); //url地址
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0); //不检查ssl,可访问https
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);  //不检查ssl,可访问https
        curl_easy_setopt(curl,CURLOPT_POSTFIELDS,POSTFIELDS); //post参数
        curl_easy_setopt(curl,CURLOPT_POST,1); //设置问非0表示本次操作为post
        curl_easy_setopt(curl,CURLOPT_VERBOSE,1); //打印调试信息

        http_header = curl_slist_append(NULL, "Content-Type:application/json;charset=UTF-8");
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, http_header);

        curl_easy_setopt(curl,CURLOPT_FOLLOWLOCATION,1); //设置为非0,响应头信息location
        curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10);
        curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10);//接收数据时超时设置,如果10秒内数据未

  
	res = curl_easy_perform(curl);
 
	if (res != CURLE_OK)
	{
		switch(res)
		{
			case CURLE_UNSUPPORTED_PROTOCOL:
				fprintf(stderr,"不支持的协议,由URL的头部指定\n");
			case CURLE_COULDNT_CONNECT:
				fprintf(stderr,"不能连接到remote主机或者代理\n");
			case CURLE_HTTP_RETURNED_ERROR:
				fprintf(stderr,"http返回错误\n");
			case CURLE_READ_ERROR:
				fprintf(stderr,"读本地文件错误\n");
			default:
				fprintf(stderr,"返回值:%d\n",res);
		}
		return -1;
	}
 
	curl_easy_cleanup(curl);
    printf("\n");
    return 0;
}

若需要发送get请求,只需注释如下代码即可,默认为get的,如下:

        curl_easy_setopt(curl,CURLOPT_POSTFIELDS,POSTFIELDS); //post参数
        curl_easy_setopt(curl,CURLOPT_POST,1); //设置问非0表示本次操作为post

参考博客:https://blog.csdn.net/ypbsyy/article/details/83617993

你可能感兴趣的:(C)