我用Poco用C++写了一个HTTP客户端,有一种情况是服务器发送一个带有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');
如何进行?
最佳答案
下面是将响应主体作为字符串获取的代码。您也可以使用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();
关于c++ - 如何使用Poco C++从HTTP服务器响应中读取图像内容?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8862772/