#define POSTURL "http://233.230.123.234:8080/tserver"//随便写的,根据实际情况写
相应的libcurl库文件可到齐官网下载
/* HTTP POST请求 */
/*
* [参数]
* SendPtr: 发送的数据;
* SendLen:发送数据的字节数目;
* RecvPtr: 接收的数据;
* RecvLen:输入是接收缓冲区的字节数目,输出是实际接收的数据字节数目;
* Timeout:超时时间,单位毫秒。0表示永久等待。
* [返回]
* 0:接收成功
* -1: 请求失败,其它错误
* -2:接收超时,只有当设置Timeout时才有可能发生
*
* */
int PRODRM_httpPOST(const void* Send,PRODRM_U32 SendLen, void* Recv, PRODRM_U32 *RecvLen, PRODRM_U32 Timeout){
CURLcode res;
Http_Response_t receiveBuff;
receiveBuff.len=0;
//初始化libCurl
curl_global_init(CURL_GLOBAL_ALL);
//創建一個easy_handle用於每次操作,easy_handle就像一個邏輯連接,用於接下來的要進行的數據傳輸。
CURL *easy_handle=curl_easy_init();
if (!easy_handle)
{
fprintf(stderr,"curl init failed\n");
return -1;
}
curl_easy_setopt(easy_handle,CURLOPT_URL,POSTURL);
curl_easy_setopt(easy_handle, CURLOPT_POSTFIELDS, Send);
curl_easy_setopt(easy_handle, CURLOPT_POSTFIELDSIZE, SendLen);
curl_easy_setopt(easy_handle, CURLOPT_POST, 1);
//註冊回調函數
curl_easy_setopt(easy_handle,CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(easy_handle, CURLOPT_WRITEDATA, (void *)&receiveBuff);
curl_easy_setopt(easy_handle,CURLOPT_VERBOSE,1);//打印调试信息
curl_easy_setopt(easy_handle,CURLOPT_HEADER,0);//设置为0去掉响应头信息,只将相应体一起传给write_data
curl_easy_setopt(easy_handle,CURLOPT_FOLLOWLOCATION,0);//设置为0,去掉响应头信息location
curl_easy_setopt(easy_handle, CURLOPT_TIMEOUT, Timeout);
//完成curl_easy_setopt的所有指定的选项,即完成传输任务
//curl_easy_perform用來連接遠程主機,執行必要的命令,并接收數據
res=curl_easy_perform(easy_handle);
memcpy(Recv, receiveBuff.data, receiveBuff.len);
*RecvLen=receiveBuff.len;
printf("--------------\n");
printf("sssh\n%s rdata%s rlen%d\n",Recv,receiveBuff.data,receiveBuff.len);
printf("--------------\n");
// for (int i=0; i<receiveBuff.len; i++) {
// printf("%02x ", ((unsigned char *)Recv)[i]);
// }
printf("resBackData %d\n",res);
curl_easy_cleanup(easy_handle);
curl_global_cleanup();
return 0;
}
//回調函數,用來接收數據的時候被調用
typedef struct
{
char* data;
int len;
} Http_Response_t;
staticint write_data(void *buffer,int size, int nmemb,void *userp)
{
Http_Response_t *pHttpResponse;
pHttpResponse = (Http_Response_t *) userp;
if(pHttpResponse->len>0)
pHttpResponse->data = (char*)realloc(pHttpResponse->data,pHttpResponse->len+size*nmemb);
else
pHttpResponse->data = (char* )malloc(size*nmemb);
memcpy(pHttpResponse->data+pHttpResponse->len,buffer,size*nmemb);
pHttpResponse->len += size*nmemb;
// printf("hgkd%s\n",userp);
return size*nmemb;
}