A little library to easily HTTP POST variables & files in Android.
This code is an merge of this Stack Overflow post and this solution put in a nice AsyncTask, with configuration and a listener for all events.
It is also updated to the newest Android API, as HttpPost and HttpClient classes are deprecated in favor of HttpURLConnection.
This tiny library is composed of 3 classes:
- HttpListener - An interface you need to implement to listen for callbacks.
- HttpConfiguration - A helper class holding the configuration & content of the HTTP POST Request to execute.
- HttpPoster - The main class - the ASyncTask that will execute the POST requets based on the given HttpConfiguration, sending back signals through the HttpListener.
In your Android Studio project, create a folder called libs, for example: ./AndroidStudioProject/MyProject/libs
Download the repository files and unpack either:
- At the root of ./AndroidStudioProjects/ then create a symbolic link from ./AndroidStudioProject/MyProject/libs/HTTPPoster to ./AndroidStudioProject/HTTPPoster/library
- The directory "library" into the ./AndroidStudioProject/MyProject/libs/ directory and rename the "library" folder to "HTTPPoster"
In your settings.gradle Project file, add the following:
include ':libs:HTTPPoster'
In your build.gradle Module file (usually "app"), add the dependency:
dependencies {
...
implementation project(':libs:HTTPPoster')
}
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import com.licryle.httpposter.HttpConfiguration;
import com.licryle.httpposter.HttpPoster;
...
HashMap<String, String> mArgs = new HashMap<>();
mArgs.put("lat", "40.712784");
mArgs.put("lon", "-74.005941");
ArrayList<File> aFileList = getMyImageFiles();
URL mEndPoint = new URL("http://www.mysite.com/HttpPostEndPoint");
HttpConfiguration mConf = new HttpConfiguration(
mEndPoint,
mArgs,
aFileList,
this, // If this class implements HttpListener
null, // Boundary for Entities - Optional
15000, // Timeout in ms for the connection operation
10000 // Timeout in ms for the reading operation
);
new HttpPoster().execute(mConf);