前些天工作中用到了調用Java的http接口,因此在網上查找了一些資料,實現了一個簡單的httppost方法,用到的是libcurl庫,資源可以在我的資源中下載,具體代碼如下:
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include "./libcurl/include/curl.h"
#include "./libcurl/include/easy.h"
using namespace std;
int sendByHttpPost(const char *callbackUrl, string responcexml)
{
CURL * curl;
struct curl_slist *headerlist=NULL;
headerlist = curl_slist_append(headerlist, "Content-Type:application/octet-stream");
//初始化libcurl庫,想用libcurl庫的函數就必須首先初始化libcurl
CURLcode code = curl_global_init(CURL_GLOBAL_ALL);
if(CURLE_OK != code)
return -1;
//初始化easy interface,想使用easy interface的api函數就必須首先初始化easy interface
curl = curl_easy_init();
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist);
//curl_easy_setopt(curl, CURLOPT_HTTPHEADER,"Content-Type:application/octet-stream");
curl_easy_setopt(curl, CURLOPT_URL, callbackUrl);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, responcexml.c_str());
curl_easy_perform(curl);
curl_easy_cleanup(curl);//釋放資源
curl_global_cleanup();//釋放資源
if (headerlist)
{
//delete headerlist;
curl_slist_free_all(headerlist);
headerlist = NULL;
}
return 0;
}
int main(int argc, char **argv)
{
const char *callbackUrl = "http://192.168.0.135:8080/basin/publiscollback/publiscollback_updateSendUserStatus.action";
string test = "測試信息";
if(sendByHttpPost(callbackUrl, test) < 0)
return -1;
system("pause");
return 0;
}