如何使用Android ndk进行HTTP请求

How to do HTTP Requests with Android ndk

本文关键字:HTTP 请求 进行 ndk 何使用 Android      更新时间:2023-10-16

我正在为android/ios编写一个纯本机应用程序,但网络代码有问题。我似乎无法编译curl,不管怎样,我都希望有一个更面向对象的库。

什么是一个好的库或方法?我目前从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.1rnHost: 182.50.154.140:8080rnConnection: closernrn";
        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;
    }
};

不过,这在大页面上会中断。

cURL是您的最佳选择。以下是您可以尝试移植cURL 的几个链接

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

如果你仍然没有成功使用cURL,尝试POCO

http://pocoproject.org/