Boost ASIO HTTPS POST请求多线程

时间:2018-12-10 01:54:12

标签: c++ ssl boost https asio

我正在尝试获取boost ASIO库来发送帖子,但过了一段时间后请求不会发送到服务器。

我得到的错误是context: unable to load ssl2 md5 routines

以下代码在多线程应用程序中并行运行以发送HTTPS请求:

HTTPSClient::HTTPSClient(URL url) :
    url(url),
    multipartBoundary(""),
    multipartCount(0),
    contentSize(0),
    ctx(io_service, boost::asio::ssl::context::sslv23_client),
    ssocket(io_service, ctx) 
{
requestStream = NULL;
bodyStream = NULL;
}

void HTTPSClient::Init(std::string methodType) {
//ctx.set_default_verify_paths();
boost::asio::ip::tcp::resolver resolver(io_service);
boost::asio::ip::tcp::resolver::query query(url.host, url.type);
boost::asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
boost::asio::connect(ssocket.lowest_layer(), endpoint_iterator);
ssocket.handshake(boost::asio::ssl::stream_base::client);
requestStream = new std::ostream(&request);
bodyStream = new std::ostringstream();

*requestStream << methodType << " " << url.urlPath << " HTTP/1.1\r\n";
*requestStream << "Host: " << url.host << "\r\n";
*requestStream << "Accept: */*\r\n";
*requestStream << "Connection: close\r\n";
}

void HTTPSClient::AddContent(std::string data) {
    *bodyStream << "\r\n" << data;
}

void HTTPSClient::SentRequest() {
    boost::asio::write(ssocket, request);
}

std::string HTTPSClient::GetResponse() {
std::string responseStr("");
boost::asio::read_until(ssocket, response, "\r\n");
std::istream response_stream(&response);
std::string http_version;
response_stream >> http_version;
response_stream >> status_code;
std::string status_message;
std::getline(response_stream, status_message);
if (!response_stream || http_version.substr(0, 5) != "HTTP/") {
    responseStr = "Invalid response\n";
    return responseStr;
}
if (status_code != 200) {
    std::cout << "Response returned with status code " << status_code;
}
// Read the response headers, which are terminated by a blank line.
boost::asio::read_until(ssocket, response, "\r\n\r\n");
// Process the response headers.
std::string header, temp;
while (std::getline(response_stream, temp) && temp != "\r") {
    header += temp;
}

// Read until EOF, writing data to output as we go.
boost::system::error_code error;
    while (boost::asio::read(ssocket, response,
            boost::asio::transfer_at_least(1), error)) {
        std::string data((std::istreambuf_iterator<char>(&response)), std::istreambuf_iterator<char>());
        responseStr.append(data);
    }
if (error != boost::asio::error::eof) {
    LOG_ERROR << url.type << ": error != boost::asio::error::eof " << error << error.message();
    throw boost::system::system_error(error);
}
return responseStr;
}

我尝试了链接https://sourceforge.net/p/asio/mailman/message/18887284/,但也没有帮助。

此外,我想知道是否可以对并行线程中运行的所有客户端请求使用相同的boost::asio::io_service io_service;boost::asio::ssl::context ctx;。在我的情况下,向其发出请求的主机进行了更改。

0 个答案:

没有答案