1. 程式人生 > >【Poco】http中傳輸json物件

【Poco】http中傳輸json物件

Poco中封裝了表單提交的功能,提交表單是非常簡單的。

Net::HTMLForm form;
form.add("name", "jack");

URI url("http://httpbin.org/post");

Net::HTTPClientSession session(url.getHost(), url.getPort());
Net::HTTPRequest req(Net::HTTPRequest::HTTP_POST, url.getPathAndQuery());

form.prepareSubmit(req);
auto& ostr = session.sendRequest(req);
form.write(ostr);

Net::HTTPResponse resp;
session.receiveResponse(resp);

如今在http中傳輸json也是比較常見的,但是Poco並沒有封裝相關介面。

先看看HTMLForm內部做了些什麼

void HTMLForm::prepareSubmit(HTTPRequest& request)
{
	if (request.getMethod() == HTTPRequest::HTTP_POST || request.getMethod() == HTTPRequest::HTTP_PUT)
	{
		if (_encoding == ENCODING_URL)
		{
			request.setContentType(_encoding);
			request.setChunkedTransferEncoding(false);
			Poco::CountingOutputStream ostr;
			writeUrl(ostr);
			request.setContentLength(ostr.chars());
		}
		else
		{
			_boundary = MultipartWriter::createBoundary();
			std::string ct(_encoding);
			ct.append("; boundary=\"");
			ct.append(_boundary);
			ct.append("\"");
			request.setContentType(ct);
		}
		if (request.getVersion() == HTTPMessage::HTTP_1_0)
		{
			request.setKeepAlive(false);
			request.setChunkedTransferEncoding(false);
		}
		else if (_encoding != ENCODING_URL)
		{
			request.setChunkedTransferEncoding(true);
		}
	}
	else
	{
		std::string uri = request.getURI();
		std::ostringstream ostr;
		writeUrl(ostr);
		uri.append("?");
		uri.append(ostr.str());
		request.setURI(uri);
	}
}

很簡單,只有在使用了post並且content-type為"application/x-www-form-urlencoded"時才會寫入表單,所以我們可以直接操作Request。

JSON::Object jo;
jo.set("name", "jack");

std::ostringstream ss;
jo.stringify(ss);
std::string s;
s = ss.str();

URI url("http://httpbin.org/post");

Net::HTTPClientSession session(url.getHost(), url.getPort());
Net::HTTPRequest req(Net::HTTPRequest::HTTP_POST, url.getPathAndQuery());

//form.prepareSubmit(req);
req.setChunkedTransferEncoding(false);
req.setContentType("application/json");
req.setContentLength(s.length());

session.sendRequest(req) << s;

Net::HTTPResponse resp;
session.receiveResponse(resp);