Android使用curl+JsonCpp实现http请求
在Android SDK开发过程中,需要进行一些网络鉴权,为了保密需要将http鉴权过程隐藏在so库中。
本文使用curl+JsonCpp库通过c++实现了http请求,源码见 github 项目 AndroidNative。
1.curl
1.1 curl概念
curl是一个开源的多协议数据传输开源库,该框架具备跨平台性,开源免费,并提供了包括HTTP、FTP、SMTP、POP3等协议的功能。使用libcurl可以方便地进行网络数据传输操作,如发送HTTP请求、下载文件、发送电子邮件等。如果想让curl支持https,需要依赖openssl,因此需要先编译OpenSSL。
1.2 curl的编译
- 编译过程见上一篇文章
https://yadiq.github.io/2024/07/02/LinuxCompileOpensslCurl/ - 编译结果见本项目源码
https://github.com/yadiq/AndroidNative/tree/main/app/src/main/jni_demo/otherlibs/curl
2.JsonCpp
2.1 JsonCpp概念
JsonCppJsonCpp 是一个 C++ 库,允许操作 JSON 值,包括序列化和反序列化字符串。它还可以在反序列化/序列化步骤中保留现有注释,使其成为一种存储用户输入文件的便捷格式。
2.2 JsonCpp的编译
- 我们使用Android NDK CMake 对源码进行编译,和curl静态库编译在一起。
- 编译过程见本项目源码
https://github.com/yadiq/AndroidNative/tree/main/app/src/main/jni_demo/otherlibs/jsoncpp
https://github.com/yadiq/AndroidNative/blob/main/app/src/main/jni_demo/CMakeLists.txt
3. 使用curl+JsonCpp实现http请求
3.1 CMake链接库
libcurl(网络协议库)如果要支持https,需要依赖libssl(SSL和TLS协议)。
而libssl(SSL和TLS协议)又依赖libcrypto(密码学算法)。
libcurl(网络协议库)如果要支持压缩传输,需要依赖zlib库。
这里我们使用前文的编译结果,OpenSSL编译后产生的 libcrypto.so libssl.so,curl编译后产生的 libcurl.a 。
使用Android系统自带的zlib库。CMake脚本见:
https://github.com/yadiq/AndroidNative/blob/main/app/src/main/jni_demo/CMakeLists.txt
3.2 JsonCpp的使用
已实现Json转string 和 string转Json。
3.2.1 头文件如下:JsonUtil.h
1 | #include <string> |
3.2.2 函数文件如下:JsonUtil.cpp
1 | #include "JsonUtil.h" |
3.3 curl实现http请求
已实现 http get请求 和 post请求。
3.3.1 头文件如下:CurlHttp.h
1 | #include "curl/curl.h" |
3.3.2 函数文件如下:CurlHttp.cpp
请在函数之前,至少调用全局初始化一次。
1 | #include "CurlHttp.h" |
3.3.3 测试文件如下:CurlTest.cpp
1 | #include "CurlTest.h" |
源码见:
https://github.com/yadiq/AndroidNative/blob/main/app/src/main/jni_demo/utils/CurlHttp.cpp