Compiling the libcurl networking library
The libcurl library is a de facto standard for native applications, which deal with numerous networking protocols. The libcurl compilation for Android on a Windows host requires some additional steps to be done. We explain them in this recipe.
Getting ready
Download the libcurl source code from the library homepage: http://curl.haxx.se/libcurl/.
How to do it...
- Since the libcurl library build process is based on
Autoconf
, we will need to generate acurl_config.h
file before actually building the library. Run theconfigure
script from the folder containing the unpacked libcurl distribution package. Cross-compilation command-line flags should be set to:--host=arm-linux CC=arm-eabi-gcc
- The
-I
parameter of theCPPFLAGS
variable should point to the/system/core/include
subfolder of your NDK folder, in our case:CPPFLAGS=”-I D:/NDK/system/core/include”
- The libcurl library can be customized in many ways. We use this set of parameters (disable all protocols except HTTP):
>configure CC=arm-eabi-gcc --host=arm-linux --disable-tftp --disable-sspi --disable-ipv6 --disable-ldaps --disable-ldap --disable-telnet --disable-pop3 --disable-ftp --without-ssl --disable-imap --disable-smtp --disable-pop3 --disable-rtsp --disable-ares --without-ca-bundle --disable-warnings --disable-manual --without-nss --enable-shared --without-zlib --without-random --enable-threaded-resolver
- The
configure
script will generate a validcurl_config.h
header file. You may find it in the accompanying materials. - Further compilation requires a usual set of
Android.mk/Application.mk
files, which is also available in the accompanying materials.
How it works…
A simplistic usage example looks like the following:
CURL* Curl = curl_easy_init(); curl_easy_setopt( Curl, CURLOPT_URL, “http://www.google.com” ); curl_easy_setopt( Curl, CURLOPT_FOLLOWLOCATION, 1 ); curl_easy_setopt( Curl, CURLOPT_FAILONERROR, true ); curl_easy_setopt( Curl, CURLOPT_WRITEFUNCTION, &MemoryCallback ); curl_easy_setopt( Curl, CURLOPT_WRITEDATA, 0 ); curl_easy_perform( Curl ); curl_easy_cleanup( Curl );
Here MemoryCallback()
is a function that handles the received data. A minimalistic unsafe implementation to dump a network response to the terminal can be as follows:
size_t MemoryCallback( void* P, size_t Size, size_t Num, void* ) { printf( (unsigned char*)P) ); }
The retrieved data will be printed on the screen in the Windows application. The same code will work like a dummy in Android, without producing any visible side effects.
There’s more…
In order to work with SSL-encrypted connections, we need to tell libcurl where our system certificates are located. This can be done with CURL_CA_BUNDLE
defined in the beginning of the curl_config.h
file:
#define CURL_CA_BUNDLE “/etc/ssl/certs/ca-certificates.crt”
See also
- Chapter 3, Networking