2015-05-13 67 views
0

我已經寫了下面的程序來從服務器獲取JSON響應。代碼是正確的,服務器的響應符合我的預期。從服務器如何在C++的.json文件中保存HTTP GET的JSON響應?

#include <boost/asio/ip/tcp.hpp> //I have not shown some header for sake of readability 

int main() 
{ 

     try 
     { 
      boost::asio::ip::tcp::iostream s; 
      s.expires_from_now(boost::posix_time::seconds(60)); 
      const std::string IP = "123.456.789.000"; 
      s.connect(IP, "83"); 

      if (!s) { 
       std::cout << "Unable to connect: " << s.error().message() << "\n"; 
      } 

      s << "GET /MY_PATH HTTP/1.1\r\n"; 
      s << "Host: 123.456.789.000:83\r\n"; 
      s << "Accept: */*\r\n"; 
      s << "Connection: close\r\n\r\n"; 

      // Checking if response is OK. 
      std::string http_version; 
      s >> http_version; 
      unsigned int status_code; 
      s >> status_code; 
      std::cout<<"\nHTTP " << status_code << std::endl; 

      std::string status_message; 
      std::getline(s, status_message); 

      if (!s || http_version.substr(0, 5) != "HTTP/") { 
       std::cout << "Invalid response\n"; 
      } 

      if (status_code != 200) { 
       std::cout << "\nResponse returned with status code " << status_code << "\n"; 
      } 

      // Processing the response headers, which were terminated by a blank line. 
      std::string header; 

      while (std::getline(s, header) && header != "\r") 
      std::cout << header << "\n"; 

      std::cout << "\n"; 

      // Writing the remaining data to output. 
      std::cout << s.rdbuf() << "\n" << std::endl; 

     }// try ends here 

     catch (std::exception& e) { 
      std::cout << "Exception: " << e.what() << "\n"; 
     } 

} 

答覆如下:

HTTP 200 
Cache-Control: no-cache 
Pragma: no-cache 
Content-Type: application/json; charset=utf-8 
Expires: -1 
Server: Microsoft 
X-AspNet-Version: 4 
X-Powered-By: ASP.NET 
Date: Wed, 13 May 2015 07:49:57 GMT 
Connection: close 
Content-Length: 345 

[{"CmdID":"30b2b2ca-376d-42bf-a931-1b92679871fc","EID":"102","CID":"00000102","NAME":"ABCD","BDAY":null,"VDATE":null,"UID":null,"ImgFileType":null,"EIMAGEBASE64STR":null},{"CmdID":"83c7d70da361-4f98-9803-1d5b7771d329","EID":"00000109","CID":"00000109","NAME":"CDEF","BDAY":null,"VDATE":null,"UID":null,"ImgFileType":null,"EIMAGEBASE64STR":null}] 

我現在想的JSON響應字符串保存到以.json文件。我怎麼能這樣做?

此時我可以存儲包含HEADER和JSON字符串的完整服務器響應。但我只對JSON字符串感興趣。

在接下來的步驟中(我已經完成了),這個json字符串將被解析並存儲到sqlite3數據庫中。但不幸的是我被困在這。

請幫忙。謝謝

+2

'//寫剩餘的數據輸出。 std :: cout << s.rdbuf()<<「\ n」<< std :: endl;'只寫入文件。有什麼問題? – Cthulhu

+0

哦......是啊!現在我很尷尬地發佈這個問題:( –

+0

@CthulhuThank你 –

回答

1

嗯,其實這是一個蛋糕散步。我很抱歉浪費你的時間。

爲了得到文件中的JSON字符串輸出,我做了以下操作。

 // Writing the remaining data to output. 
     freopen("JSONoutput.json","w",stdout);  
     std::cout << s.rdbuf() << "\n" << std::endl; 

freopen函數():重複利用流要麼打開由文件名或改變其訪問所指定的文件mode.If新的文件名被指定,則該函數首先嚐試關閉已經與流相關聯的任何文件(第三參數)並將其解除關聯。然後,無論該流是否成功關閉,freopen都會打開由filename指定的文件,並將其與流相關聯,就像fopen使用指定的模式一樣。

這將創建一個文件JSONoutput.json,唯一的JSON字符串被存儲到它,沒有別的。