2014-09-05 32 views
1

我正在爲android/ios編寫純原生應用程序,並且遇到網絡代碼問題。我似乎無法得到curl編譯,無論哪種方式我寧願有一個更面向對象的庫。如何使用Android執行HTTP請求ndk

什麼是一個好的圖書館來做到這一點或方法?我目前使用HTTP請求獲取json的方法是使用SDL2_Net的代碼

class HTTPRequest{ 
protected: 
    std::map<std::string, std::string> uris; 
    std::string url; 

public: 
    std::string host; 

    HTTPRequest(std::string path) : url(path), host("182.50.154.140") {} 

    void addURI(std::string parameter, std::string value){ 
     uris[parameter] = value; 
    } 

    std::string sendRequest(bool useCookie=false){ 
     std::string temppath = url; 
     if(!uris.empty()){ 
      temppath += '?'; 
      for(auto &a : uris){ 
       temppath += a.first; 
       temppath += '='; 
       temppath += a.second; 
       temppath += '&'; 
      } 
     } 
     IPaddress* addr = new IPaddress; 
     SDLNet_ResolveHost(addr, host.c_str(), 8080); 
     TCPsocket sock = SDLNet_TCP_Open(addr); 
     std::string a = "GET ", b = " HTTP/1.1\r\nHost: 182.50.154.140:8080\r\nConnection: close\r\n\r\n"; 
     std::string c = a+temppath+b; 
     SDLNet_TCP_Send(sock, c.c_str(), c.length()); 
     std::string d; 
     char* buf = new char[1024]; 
     while(SDLNet_TCP_Recv(sock, buf, 1024) > 0){ 
      d += buf; 
      delete[] buf; 
      buf = new char[1024]; 
     } 
     delete[] buf; 
     SDLNet_TCP_Close(sock); 
     int p = d.find("{"); 
     d.erase(0, p-1); 
     return d; 
    } 
}; 

雖然這在大型頁面上會中斷。

回答

2

cURL是你最好的選擇。這裏有幾個鏈接,您可以嘗試移植捲曲

http://thesoftwarerogue.blogspot.com/2010/05/porting-of-libcurl-to-android-os-using.html https://github.com/jahrome/curl-android

如果你仍然不使用捲曲有成功,嘗試POCO

http://pocoproject.org/

+1

其實我設法捲曲使用編譯在這個網站上的另一個答案,但我不得不修改一些命令,使他們與最新版本的工作。 – ruler501 2014-09-08 21:47:17