这段代码的问题在于没有正确处理HTTP响应的分块传输。在使用boost::asio::read函数读取响应数据时,应该使用boost::asio::transfer_all参数来确保读取完整的响应。另外,应该将响应缓冲区的数据追加到一个字符串变量中,以便正确处理分块传输的响应。

以下是修改后的代码:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <boost/asio.hpp>

using boost::asio::ip::tcp;

// 下载accession号并保存到文件
void downloadAccessionNumbers(const std::string& geneName, const std::string& outputFile)
{
    try {
        // 创建IO上下文
        boost::asio::io_context io_context;

        // 解析NCBI服务器的IP地址和端口号
        tcp::resolver resolver(io_context);
        tcp::resolver::results_type endpoints = resolver.resolve("www.ncbi.nlm.nih.gov", "http");

        // 创建socket并连接到NCBI服务器
        tcp::socket socket(io_context);
        boost::asio::connect(socket, endpoints);

        // 发送HTTP GET请求
        std::string request = "/bioproject/?term=" + geneName + "&report=docsum&format=text";
        boost::asio::write(socket, boost::asio::buffer("GET " + request + " HTTP/1.1\r\n"
                                                       "Host: www.ncbi.nlm.nih.gov\r\n"
                                                       "Connection: close\r\n\r\n"));

        // 读取服务器响应
        std::ofstream outputFileStream(outputFile);
        std::string response;
        std::vector<char> responseBuffer(1024);
        std::size_t bytesRead = 0;
        while ((bytesRead = boost::asio::read(socket, boost::asio::buffer(responseBuffer), boost::asio::transfer_all())) > 0)
        {
            // 将响应缓冲区中的数据追加到字符串
            response.append(responseBuffer.data(), bytesRead);
        }

        // 在响应中搜索accession号,并将其写入文件
        size_t found = response.find("ACCESSION ");
        while (found != std::string::npos)
        {
            size_t end = response.find("\n", found);
            std::string accession = response.substr(found + 10, end - found - 10);
            outputFileStream << accession << std::endl;
            found = response.find("ACCESSION ", found + 1);
        }

        // 关闭文件和socket
        outputFileStream.close();
        socket.close();
    }
    catch (std::exception& e) {
        std::cerr << "Exception: " << e.what() << std::endl;
    }
}

int main()
{
    std::string geneName = "phoD";
    std::string outputFile = "accession_numbers.txt";

    downloadAccessionNumbers(geneName, outputFile);

    return 0;
}
下面的代码输出内容为空请修改代码:#include iostream#include fstream#include string#include vector#include boostasiohppusing boostasioiptcp; 下载accession号并保存到文件void downloadAccessionNumbersconst stdstring& geneName cons

原文地址: https://www.cveoy.top/t/topic/ingX 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录