加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

C++ Rest SDK 客户端,服务端例子代码

(2014-10-23 13:48:51)
标签:

restsdk

客户端

服务端

casablanca

分类: RestSDK

最近利用t微软的开源库C++ Rest SDK 做了一个客户端服务端信息交互的小例子,现在把客户端,服务端的例子代码贴出来,与大家共享。关于Rest SDK 在工程中的使用参考其他文档。

服务端:

#include "stdafx.h"
#include

using namespace web;
using namespace http;
using namespace utility;
using namespace http::experimental::listener;
using namespace std;

class MyListener
{
public:
 MyListener(const uri&url);
 ~MyListener();
 http_listener m_listener;
 void handle_post(http_request request);
};

MyListener::MyListener(const uri&url) :m_listener(http_listener(url))
{
 m_listener.support(methods::POST, bind(&MyListener::handle_post, this, placeholders::_1));
}

MyListener::~MyListener()
{
 m_listener.close().wait();
}

void MyListener::handle_post(http_request request)
{
 setlocale(LC_ALL, "");
 wstring str1 = request.to_string();
 auto str2 = request.extract_string().get();

 request.reply(status_codes::OK,L"goodbye");
}

int _tmain(int argc, _TCHAR* argv[])
{
 wstring port = U("3456");
 wstring address = L"http://localhost:";
 address.append(port);

 uri_builder url(address);
 url.append_path(U("abc/cd"));
 unique_ptr listener;
 listener.reset(new MyListener(url.to_uri()));
 ucout << "waiting for request at " <<url.to_string()<< endl;
 listener->m_listener.open().wait();

 string line;
 getline(cin, line);

 return 0;
}

 

客户端:

#include "stdafx.h"
#include
#include
using namespace std;
using namespace web;
using namespace web::http;
using namespace utility;
using namespace http::client;
using namespace web::json;
using namespace utility::conversions;

wstring  StringToWString(const string& s)
{
 wstring wszStr;

 int nLength = MultiByteToWideChar(CP_ACP, 0, s.c_str(), -1, NULL, NULL);
 wszStr.resize(nLength);
 wchar_t* lpwszStr = new wchar_t[nLength];
 MultiByteToWideChar(CP_ACP, 0, s.c_str(), -1, lpwszStr, nLength);
 wszStr = lpwszStr;
 delete[] lpwszStr;

 return wszStr;
}


int _tmain(int argc, _TCHAR* argv[])
{
 wstring port = L"3456";
 wstring address = L"http://localhost:";
 address.append(port);
 http_client client(address);

 //读取二进制文件
 ifstream fin("D:\\b.jpg", ios::_Nocreate|ios::binary);
 fin.seekg(0, ios::end);
 int fileLength = fin.tellg();
 char *buf = new char[fileLength+2];
 fin.seekg(0, 0); 
 if (!fin.eof())
 {
  fin.read(buf, fileLength);
 }

 buf[fileLength + 1] = '$';

 

 uri_builder builder(L"/abc/cd");
 builder.append_query(L"name",buf);
 wstring s = builder.to_string();
 http_response response = client.request(methods::POST, builder.to_string()).get();
 delete []buf;
 if (response.status_code() == status_codes::OK)
 {
  setlocale(LC_ALL, "");
  wstring  ss = response.extract_string().get();
  ucout << ss << endl;
 }

 return 0;
}

 

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有