2012-01-14 185 views
3

我正在使用Poco編寫C++中的HTTP客戶端,並且存在服務器使用jpeg圖像內容(以字節爲單位)發送響應的情況。我需要客戶端來處理響應並從這些字節生成一個jpg圖像文件。如何使用Poco C++從HTTP服務器響應中讀取圖像內容?

我搜索了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'); 

如何繼續?

回答

-8

不要重新發明輪子。正確地做HTTP很難。使用現有的庫,如libcurl。

+6

我不推倒重來,我使用波科。 – 2012-01-14 16:03:49

+0

Leif,如果Poco包含一個HTTP庫,並且您將使用它,那麼您將不必解析Content-Length。 – 2012-01-15 10:32:17

+0

如果你知道用Poco查找Content-Length而不用手動解析的方法,那你爲什麼不告訴我它是什麼? – 2012-01-17 22:29:43

2

以下是將響應正文作爲字符串獲取的代碼。您也可以直接將它寫入帶有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(); 
+0

我不得不用二進制寫出來,才能正常工作:outfile.open(「myfile.jpg」,ios_base :: binary); – ryatkins 2013-09-15 23:02:16

+0

@ryatkins你在窗戶上? – Homer6 2013-09-15 23:18:06

+0

是的,在Windows上。否則,我的圖片下載會出現損壞。你認爲這是Windows特有的嗎? – ryatkins 2013-09-16 13:56:54

相關問題