Linux環境下C++訪問web服務——使用libcurl庫調用http接口發送解析json數據

一、背景

這兩天由於一些原因研究了研究如何在客戶端C++代碼中調用web服務端接口,需要訪問url,並傳入json數據,拿到返回值,並解析。
 現在的情形是遠程服務端的接口參數和返回類型都是json的字符串。所以我們主要做的就是:連接遠程url、找到接口,將基本類型的數據封裝成json數據傳入接口,然後獲取返回值,並解析返回的json數據。
 這裏需要用到的庫就有url庫、json庫,大致瞭解了,接下來就要下載包進行配置了。

二、配置環境

首先需要安裝curl庫和json庫,安裝詳情如下:

  • 安裝curl庫

1.下載:wget http://curl.haxx.se/download/curl-7.38.0.tar.gz (如果下載不了,直接在瀏覽器打開這個網址下載下來)
2.解壓:tar -xzvf curl-7.38.0.tar.gz
3.安裝:

cd curl-7.38.0
./configure
sudo make
sudo make install

4.查看/usr/include目錄下有沒有curl文件夾,沒有的話需要將解壓包/curl-7.38.0/include中的curl拷貝過去
5.查看/usr/local/lib/目錄下有沒有libcurl.so.4.3.0和libcurl.so,沒有的話將/curl-7.38.0/lib/.libs/libcurl.so.4.3.0拷貝到/usr/local/lib/下,並建立軟鏈接:ln -s libcurl.so.4.3.0 libcurl.so
6.將路徑加入系統查找路徑中:

sudo vim /etc/ld.so.conf.d/libc.conf 
將目錄/usr/local/lib寫入該文件中
執行sudo ldconfig

7 安裝完成

  • 安裝json庫

1.下載JsonCpp:http://sourceforge.net/projects/jsoncpp/files/
2.下載scons:http://sourceforge.net/projects/scons/files/scons/2.1.0/scons-2.1.0.tar.gz/download
3.解壓scons-2.1.0.tar.gz:tar -zvxf scons-2.1.0.tar.gz
4.進入解壓目錄scons-2.1.0,執行命令:sudo python setup.py install
5.解壓jsoncpp:tar -zvxf jsoncpp-src-0.5.0.tar.gz
6.進入jsoncpp解壓目錄下,執行命令:sudo scons platform=linux-gcc
7.將/jsoncpp-src-0.5.0/include/目錄下的json文件夾拷貝到/usr/include/
8.將jsoncpp-src-0.5.0/libs/linux-gcc-4.9.1/目錄下的libjson_linux-gcc-4.9.1_libmt.so和libjson_linux-gcc-4.9.1_libmt.a 拷貝到/usr/local/lib/,併爲了方便使用,將其重命名爲libjson.so

三、編寫代碼

代碼名稱:getInfo.cpp

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <curl/curl.h>
#include <curl/easy.h>
#include <string.h>
#include <json/json.h>
#include <iconv.h>
#include <iostream>
#include <sstream>
using namespace std;
 
size_t push_string(void* buffer, size_t size, size_t nmemb, void* stream)
{
    string data((const char*)buffer, (size_t) size * nmemb);
    *((stringstream*) stream) << data << endl;
    return size*nmemb;
}
 
char *send_post(char *url, char *param)
{
        std::stringstream res_str;
 
	CURL *curl_handle = NULL;
	CURLcode curl_res;
	curl_res = curl_global_init(CURL_GLOBAL_ALL);
    
    //  printf("param is: %s\n", param);
	if(curl_res == CURLE_OK)
	{
		curl_handle = curl_easy_init();
		if(curl_handle != NULL)
		{
			curl_easy_setopt(curl_handle, CURLOPT_URL, url);
			curl_easy_setopt(curl_handle, CURLOPT_POST, 1);
			curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDSIZE, strlen(param));
			curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDS, param);
			curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYPEER, 0);
			curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYHOST, 0);
			curl_easy_setopt(curl_handle, CURLOPT_TIMEOUT, 30);
			curl_easy_setopt(curl_handle, CURLOPT_CONNECTTIMEOUT, 10L);
			curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, push_string);
                        curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, &res_str);
                        curl_easy_setopt(curl_handle, CURLOPT_HEADER, 0L);
            
                        struct curl_slist *pList = NULL;
                        pList = curl_slist_append(pList,"Content-Type: application/json;charset=utf-8");
 
                        curl_easy_setopt(curl_handle, CURLOPT_HTTPHEADER, pList);
                        curl_res = curl_easy_perform(curl_handle);
			if(curl_res != CURLE_OK)
			{
				printf("curl_easy_perform error, err_msg:[%ld]\n", curl_res);
			}
			curl_easy_cleanup(curl_handle);
		}
	}
	else
	{
		printf("CURL ERROR : %s", curl_easy_strerror(curl_res));
	}
 
        std::string str_json = res_str.str();
	char *str;
        str = (char *)malloc(200);
        strcpy(str, str_json.c_str());
        return str;
}
 
//解析json格式的返回值  
void get_ret_info(char *res_str, char *flag, char *password, char *msg)
{
	Json::Reader json_reader;
	Json::Value json_value;
	if(json_reader.parse(res_str, json_value))
	{
		std::string flag1 = json_value["id"].asString();
		std::string password1 = json_value["password"].asString();
		std::string msg1 = json_value["msg"].asString();
 
		strcpy(flag, flag1.c_str());
		strcpy(password, password1.c_str());
		strcpy(msg, msg1.c_str());
	}
}
 
int main(int argc, char *argv[])
{
	char url[100] = "http://172.16.10.138:8888/ServerX/doRecog";	//服務端url
	char param[500] = {0};	//輸入參數
	char *res_str;	//返回數據
    
        //構造json格式的參數
        Json::Value item;
		item["username"] = Json::Value("test");
   		item["paramdata"] = Json::Value("==2==NULL==");
   		item["signdata"] = Json::Value("NULL");
   		item["imgtype"] = Json::Value("jpg");
 
        std::string str = item.toStyledString();
        strcpy(param, );
    
	res_str = send_post(url, (char*)str.c_str());
	printf("return string is: %s", res_str);
	
	char flag[10] = {0};
	char password[30] = {0};
	char msg[200] = {0};
	get_ret_info(res_str, flag, password, msg);
}

三、編譯

  • 手動編譯
g++ -c getInfo.cpp -o getInfo.o
g++ -o getInfo.exe -L /usr/local/lib -lcurl -ljson getInfo.o
  • 自動編譯
#x86 complie config
CC=g++
LD=g++
CFLAGS=-Wall -DLDAP_DEPRECATED=1 -I ./include/
 
ARCH=$(shell getconf LONG_BIT)
 
ifeq ($(DBGEN),1)
CFLAGS += -g
endif
 
ifeq ($(ARCH),32)
LIBDIR = /usr/local/lib/
BINDIR = ./
CFLAGS += -Dx86
else
LIBDIR = /usr/local/lib/
BINDIR = ./
endif
 
BINLIBS=-L $(LIBDIR) -lcurl -ljson
EXENAME1=getPasswd
DEBUG=
EXEEXT=.exe
 
TARGETBIN1 = $(EXENAME1)$(DEBUG)$(EXEEXT) 
 
 
BINOBJS1 = getPasswd.o
 
all: $(TARGETBIN1) 
 
.cpp.o:
	$(CC) $(CFLAGS) $(XFLAGS) -c $< -o $@
 
.cpp.b:
	$(CC) $(CFLAGS) $(XFLAGS) -c $< -o $@
 
$(TARGETBIN1): $(BINOBJS1)
	$(LD) -o $(BINDIR)$(TARGETBIN1) $(BINOBJS1) $(BINLIBS)
 
clean:
	rm -f *.o $(BINDIR)$(TARGETBIN1) 

四、參考文章

  1. 安裝curl:https://blog.csdn.net/makenothing/article/details/39250491
  2. 安裝json庫:https://blog.csdn.net/makenothing/article/details/39250491
  3. https://blog.csdn.net/weixin_39568041/article/details/83659649
  4. https://www.cnblogs.com/chechen/p/7261607.html
  5. https://blog.csdn.net/g1269420003/article/details/89349569
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章