【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);

 

 

 

你可能感兴趣的:(Poco,C++)