码迷,mamicode.com
首页 > Web开发 > 详细

测试JSON RPC远程调用(JSON客户端)

时间:2014-10-21 21:40:45      阅读:545      评论:0      收藏:0      [点我收藏+]

标签:blog   http   io   os   ar   java   for   sp   div   

#include <string>
#include <iostream>

#include <curl/curl.h>

/*
标题:JSon客户端
Author: Kagula
LastUpdateDate:2014-05-17
描述:测试JSON RPC远程调用
测试环境:Windows 8.1、Visual Studio 2013 SP1
         curl-7.36.0
		 CPPCMS 1.0.4(JSON服务端)
		 Java Servlet (JSON服务端)
*/

static std::string *DownloadedResponse;
static int writer(char *data, size_t size, size_t nmemb, std::string *buffer_in)
{

	// Is there anything in the buffer?  
	if (buffer_in != NULL)
	{
		// Append the data to the buffer    
		buffer_in->append(data, size * nmemb);

		// How much did we write?   
		DownloadedResponse = buffer_in;

		return size * nmemb;
	}

	return 0;

}

std::string GetJsonByPostMethod(std::string URL,std::string jsonObj)
{
	CURL *curl;
	CURLcode res;
	curl = curl_easy_init();

	if (curl)
	{
#ifndef _DEBUG
		curl_easy_setopt(curl, CURLOPT_TIMEOUT, 1);//Release模式下规定超时为一秒
#endif
		curl_easy_setopt(curl, CURLOPT_URL, URL.c_str());
		curl_easy_setopt(curl, CURLOPT_POSTFIELDS, jsonObj.c_str());
		curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, jsonObj.length());
		//curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
		curl_slist *plist = curl_slist_append(NULL,
			"Content-Type:application/json;charset=UTF-8");
		curl_easy_setopt(curl, CURLOPT_HTTPHEADER, plist);
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writer);
		res = curl_easy_perform(curl);

		if (CURLE_OK == res)
		{
			char *ct;
			res = curl_easy_getinfo(curl, CURLINFO_CONTENT_TYPE, &ct);
			if ((CURLE_OK == res) && ct)
				return *DownloadedResponse;
		}
	}
}

int main(int argc, char *argv[])
{
	std::string url = "localhost:8080/WageQuery/JsonServer";//"http://localhost:8080/calc";
	std::string jsonObj = "{\"method\":\"div\",\"params\":[12,4],\"id\":1}";//"{\"method\": \"hello\",\"name\" : \"lijun\"}";

	std::string  strR = GetJsonByPostMethod(url, jsonObj);

	std::cout << strR << std::endl;

	return 0;
}

测试JSON RPC远程调用(JSON客户端)

标签:blog   http   io   os   ar   java   for   sp   div   

原文地址:http://blog.csdn.net/lee353086/article/details/40350005

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!