我正在用Poco用C++编写一个超文本传输协议客户端,在这种情况下,服务器会发送一个带有jpeg图像内容(以字节为单位)的响应。我需要客户端处理响应,并从这些字节生成一个jpg图像文件。
我在Poco库中搜索了合适的函数,但没有找到。看起来唯一的方法就是手动完成。
这是我代码的一部分。它接收响应并使输入流从图像内容的开头开始。
/* Get response */
HTTPResponse res;
cout << res.getStatus() << " " << res.getReason() << endl;
istream &is = session.receiveResponse(res);
/* Download the image from the server */
char *s = NULL;
int length;
std::string slength;
for (;;) {
is.getline(s, '\n');
string line(s);
if (line.find("Content-Length:") < 0)
continue;
slength = line.substr(15);
slength = trim(slength);
stringstream(slength) >> length;
break;
}
/* Make `is` point to the beginning of the image content */
is.getline(s, '\n');如何继续?
发布于 2012-07-25 02:45:25
下面是以字符串形式获取响应体的代码。你也可以用ofstream把它直接写到一个文件中(见下文)。
#include <iostream>
#include <sstream>
#include <string>
#include <Poco/Net/HTTPClientSession.h>
#include <Poco/Net/HTTPRequest.h>
#include <Poco/Net/HTTPResponse.h>
#include <Poco/Net/Context.h>
#include <Poco/Net/SSLManager.h>
#include <Poco/StreamCopier.h>
#include <Poco/Path.h>
#include <Poco/URI.h>
#include <Poco/Exception.h>
ostringstream out_string_stream;
// send request
HTTPRequest request( HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1 );
session.sendRequest( request );
// get response
HTTPResponse response;
cout << response.getStatus() << " " << response.getReason() << endl;
// print response
istream &is = session.receiveResponse( response );
StreamCopier::copyStream( is, out_string_stream );
string response_body = out_string_stream.str();要直接写入文件,可以使用以下命令:
// print response
istream &is = session->receiveResponse( response );
ofstream outfile;
outfile.open( "myfile.jpg" );
StreamCopier::copyStream( is, outfile );
outfile.close();发布于 2012-01-14 23:41:00
不要重复发明轮子。正确地做HTTP是很难的。使用现有的库,如libcurl。
https://stackoverflow.com/questions/8862772
复制相似问题