HTTP Post请求天气信息(基于curl库 )

通过curl命令进行http post带参数请求:

# curl -d "参数" "url"

若在body中上传json参数,如下所示:

# curl -H "Content-Type:application/json" -X POST --data (json.data) URL
如下示例:以http post方式查询长沙的天气

基于curl库实现http post请求天气信息,代码示例:

#include <stdio.h>
#include "curl/curl.h"

#define POSTFIELDS "city=changsha&appkey=8010132dcf54491a4eaa387f4db61774"

size_t recv_data(void *ptr, size_t size, size_t nmemb, void *stream) 
{
    printf("recv_data:%s\n",(char *)ptr);
    return size * nmemb;
}

int main(int argc,char *argv[])
{
	struct curl_slist* headers = NULL;
    char *url = "https://way.jd.com/he/freeweather";
	CURL *curl;
	CURLcode res;
    curl = curl_easy_init();
	if( NULL != curl )
	{
		curl_easy_setopt(curl, CURLOPT_URL, url);				//设置URL
		curl_easy_setopt(curl, CURLOPT_POSTFIELDS, POSTFIELDS); //设置post参数
		curl_easy_setopt(curl, CURLOPT_POST, 1);         //设置http发送协议为post
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, recv_data);//设置接收回调函数
		res = curl_easy_perform(curl);    //执行 
		curl_easy_cleanup(curl);  //释放
	}
    return 0;
}

猜你喜欢

转载自blog.csdn.net/fangye945a/article/details/86530858