---
title: "使用libcurl提交POST请求"
author: "finux"
date: "2010-07-17T22:14:08Z"
tags: []
categories: ["编程语言"]
slug: "libcurl-post"
draft: false
lastmod: "2010-07-17T22:42:38Z"
id: 715247
url: "https://finux.iteye.com/blog/715247"
---

最近在学习libcurl，并利用它提交POST请求，可是返回的响应总是无从验证该次POST请求是否成功提交了。

1\. 先看下根据firebug提交的一次成功的请求，这里以login我喜欢上的xiami为例，嘻嘻~

 

1.1 本次POST请求的HTTP交互

![](http://dl.iteye.com/upload/picture/pic/67261/a9852e62-f4c1-3d51-9389-776e2fe296c0.png)

 

1.2 POST

![](http://dl.iteye.com/upload/picture/pic/67263/f54fc236-dfdd-3838-bfe5-fe5eba5d28ff.png)

 

1.3 经server端redirect的GET

![](http://dl.iteye.com/upload/picture/pic/67265/40ea8ff2-389c-3db0-9dce-5fd741a35cc5.png)

 

2\. OK，接下来看下使用libcurl向xiami发送POST请求

 

2.1 使用libcurl的大概流程  
curl\_easy\_init()  
curl\_easy\_setopt()  
curl\_easy\_perform()  
curl\_easy\_cleanup()  
呵呵~超简单的吧，具体的意思这里就不详细说了，参见[http://curl.haxx.se/libcurl/c/](http://curl.haxx.se/libcurl/c/)

 

2.2 再来看简单的代码

```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>

#define POSTURL "http://www.xiami.com/member/login"
#define POSTFIELDS "email=myemail@163.com&password=mypassword&autologin=1&submit=登 录&type="
#define FILENAME "curlposttest.log"

size_t write_data(void *buffer, size_t size, size_t nmemb, void *userp);

int main(int argc, char *argv[]) {
	CURL *curl;
	CURLcode res;
	FILE *fptr;
	struct curl_slist *http_header = NULL;

	if ((fptr = fopen(FILENAME, "w")) == NULL) {
		fprintf(stderr, "fopen file error: %s\n", FILENAME);
		exit(1);
	}

	curl = curl_easy_init();
	curl_easy_setopt(curl, CURLOPT_URL, POSTURL);
	curl_easy_setopt(curl, CURLOPT_POSTFIELDS, POSTFIELDS);
	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
	curl_easy_setopt(curl, CURLOPT_WRITEDATA, fptr);
	curl_easy_setopt(curl, CURLOPT_POST, 1);
	curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
	curl_easy_setopt(curl, CURLOPT_HEADER, 1);
	curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
	curl_easy_setopt(curl, CURLOPT_COOKIEFILE, "/Users/zhu/CProjects/curlposttest.cookie");
	res = curl_easy_perform(curl);
	curl_easy_cleanup(curl);
}

size_t write_data(void *buffer, size_t size, size_t nmemb, void *userp) {
	FILE *fptr = (FILE*)userp;
	fwrite(buffer, size, nmemb, fptr);
}
```

 

2.3 说下这当中的一些操作吧

CURLOPT\_URL: URL地址  
CURLOPT\_POSTFIELDS: POST参数  
CURLOPT\_WRITEFUNCTION: 对返回的数据进行操作的函数地址  
CURLOPT\_WRITEDATA: 设置WRITEFUNCTION的第四个参数值  
CURLOPT\_POST: 设置为非0表示本次操作为POST  
CURLOPT\_VERBOSE: 设置为非0在执行时打印请求信息  
CURLOPT\_HEADER: 设置为非0将响应头信息同响应体一起传给WRITEFUNCTION  
CURLOPT\_FOLLOWLOCATION: 设置为非0，响应头信息Location

**CURLOPT\_COOKIEFILE: 哈哈，这个实在是太重要了，我之前尝试了好多次没法验证该次POST是否成功的原因就是没有设置这个罗。设置对应的COOKIEFILE路径，该路径文件并不一定需要在物理磁盘上实际存在**

 

2.4 接下来是成功返回的结果哦，呵呵，下面截图当中的zhuzhu可以为证，不好意思，xiami上取了个比较CUO的名字~

![](http://dl.iteye.com/upload/picture/pic/67267/dd3d3e22-c833-3d86-9574-f98ed5cd0621.png)