I once made the class below. I don't know if it is up to date, so you might need to tweak it somewhat. You can call it using:
RestWrapperAsync wrapper = new RestWrapperAsync();
wrapper.SetUp("url");
wrapper.setFormBodyJson(jsonArray); //or setform..
wrapper.SetAuthentication("name", "password");
wrapper.SetResponseCallback(this);
wrapper.execute();
public class RestWrapperAsync extends AsyncTask<Void, Integer, Object> {
private WeakReference<ResponseCallback> mResponseCallback;
private WeakReference<ProgressCallback> mProgressCallback;
public interface ResponseCallback {
public void OnRequestSuccess(String response);
public void OnRequestError(Exception ex);
}
public interface ProgressCallback {
public void OnProgressUpdate(int progress);
}
public void SetResponseCallback(ResponseCallback callback){
mResponseCallback = new WeakReference<ResponseCallback>(callback);
}
public void setProgressCallback(ProgressCallback callback) {
mProgressCallback = new WeakReference<ProgressCallback>(callback);
}
private boolean getDetailsFromPost = false;
public void SetGetDetailsFromPost(boolean value){
getDetailsFromPost = value;
}
HttpURLConnection mConnection;
String mFormBody;
File mUploadFile;
String mUploadFileName;
JSONArray mFormBodyJSONArray;
JSONObject mFormBodyJSON;
/**
* Sets up the connection and the url
* @param siteUrl
*/
public void SetUp(String siteUrl, boolean doOutput){
try
{
URL url=null;
if (siteUrl!=null) {
url = new URL(siteUrl);
}
else {
url = new URL("https://xxxx");
}
mConnection = (HttpURLConnection) url.openConnection();
mConnection.setReadTimeout(10000 /* milliseconds */);
mConnection.setConnectTimeout(5000 /* milliseconds */);
mConnection.setRequestMethod("GET"); //set to get initially
if (doOutput){
//mConnection.setDoOutput(true);
mConnection.setDoInput(true);
}
else
mConnection.setDoInput(true);
}
catch (Exception ex){
Log.e("ERROR","Exception setting up connection:"+ex.getMessage());
}
}
/**
* Sets up form body for post requests
* @param formData
*/
public void setFormBody(List<NameValuePair> formData){
if (formData == null) {
mFormBody = "";
return;
}
try
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < formData.size(); i++) {
NameValuePair item = formData.get(i);
sb.append( URLEncoder.encode(item.getName(),"UTF-8") );
sb.append("=");
sb.append( URLEncoder.encode(item.getValue(),"UTF-8") );
if (i != (formData.size() - 1)) {
sb.append("&");
}
}
mFormBody = sb.toString();
}
catch(Exception ex){
Log.e("ERROR","Exception setting up connection:"+ex.getMessage());
}
}
/**
* Sets up form body for post request
* @param object
*/
public void setFormBodyJson(JSONArray object){
mFormBodyJSONArray = object;
}
/**
* Sets up form body for post request
* @param object
*/
public void setFormBodyJson(JSONObject object){
mFormBodyJSON = object;
}
/**
* Write out Json array to outputstream
* @param charset
* @param output
* @throws IOException
*/
private void writeFormDataJSON(JSONArray charset, OutputStream output) throws IOException {
try
{
output.write(charset.toString().getBytes());
output.flush();
}
finally
{
if (output != null) {
output.close();
}
}
}
/**
* Write out Json object to outputstream
* @param charset
* @param output
* @throws IOException
*/
private void writeFormDataJSON(JSONObject charset, OutputStream output) throws IOException {
try
{
output.write(charset.toString().getBytes());
output.flush();
}
finally
{
if (output != null) {
output.close();
}
}
}
/**
* Write out Charset to outputStream
* @param charset
* @param output
* @throws IOException
*/
private void writeFormData(String charset, OutputStream output) throws IOException {
try
{
output.write(mFormBody.getBytes(charset));
output.flush();
}
finally
{
if (output != null) {
output.close();
}
}
}
/**
* Sets up authentication
* @param username
* @param password
*/
public void SetAuthentication(String username, String password){
if (this.mConnection==null) {
Log.e("RestWrapper","Autentication called, but connection = null");
}
else
attachBasicAuthentication(mConnection,username,password);
}
/**
* Attaches authorization to header
* @param connection
* @param username
* @param password
*/
private static void attachBasicAuthentication(URLConnection connection, String username, String password) {
//Add Basic Authentication Headers
String userpassword = username + ":" + password;
String encodedAuthorization =
Base64.encodeToString(userpassword.getBytes(), Base64.NO_WRAP);
connection.setRequestProperty("Authorization", "Basic "+ encodedAuthorization);
}
public void setUploadFile(File file, String fileName) {
mUploadFile = file;
mUploadFileName = fileName;
}
/**
* Do network connection in background
*/
@Override
protected Object doInBackground(Void... arg0) {
return CallService(true);
}
/**
* The actual call to the web api's
* @param isAsyn
* @return
*/
public Object CallService(boolean isAsyn){
try
{
String charset = Charset.defaultCharset().displayName();
if (mFormBodyJSON != null) {
mConnection.setDoOutput(true);
mConnection.setRequestMethod("POST");
mConnection.setRequestProperty("Content-Type","application/json; charset="+charset);
mConnection.setFixedLengthStreamingMode(mFormBodyJSON.toString().length());
}
else if (mFormBodyJSONArray != null) {
mConnection.setDoOutput(true);
mConnection.setRequestMethod("POST");
mConnection.setRequestProperty("Content-Type","application/json; charset="+charset);
mConnection.setFixedLengthStreamingMode(mFormBodyJSONArray.toString().length());
}
else if (mFormBody != null) {
mConnection.setDoOutput(true);
mConnection.setRequestMethod("POST"); //change to post
mConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset="+charset);
mConnection.setFixedLengthStreamingMode(mFormBody.length());
}
if (isAsyn)
this.publishProgress(1);
mConnection.connect();
if (mFormBodyJSON!=null){
OutputStream out = mConnection.getOutputStream();
writeFormDataJSON(mFormBodyJSON, out);
}
else if (mFormBodyJSONArray!=null){
OutputStream out = mConnection.getOutputStream();
writeFormDataJSON(mFormBodyJSONArray, out);
}
else if (mFormBody != null) {
OutputStream out = mConnection.getOutputStream();
writeFormData(charset, out);
}
int status=0;
status = mConnection.getResponseCode();
if (isAsyn)
this.publishProgress(2);
if (status == 204){
if (!getDetailsFromPost){
return Constants.DATAPOSTEDCORRECTLY;
}
}
if (status >= 300){
String message = mConnection.getResponseMessage();
InputStream in = mConnection.getErrorStream();
String encoding = mConnection.getContentEncoding();
if (encoding == null) {
encoding = "UTF-8";
}
if (in != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(in, encoding));
message = reader.readLine();
message = message.replace('"', ' ');
message = message.trim();
return new HttpResponseException(status, message);
}
}
//Get response data back
InputStream in = mConnection.getInputStream();
String encoding = mConnection.getContentEncoding();
if (encoding == null) {
encoding = "UTF-8";
}
this.publishProgress(3);
BufferedReader reader = new BufferedReader(new InputStreamReader(in, encoding));
String result = reader.readLine();
return result;
}
catch (Exception ex){
return ex;
}
finally {
if (mConnection != null) {
mConnection.disconnect();
}
}
}
@Override
protected void onProgressUpdate(Integer... values) {
if (mProgressCallback != null && mProgressCallback.get() != null) {
mProgressCallback.get().OnProgressUpdate(values[0]);
}
}
@Override
protected void onPostExecute(Object result) {
if (mResponseCallback != null && mResponseCallback.get() != null) {
if (result instanceof String) {
mResponseCallback.get().OnRequestSuccess((String) result);
}
else if (result instanceof Exception) {
mResponseCallback.get().OnRequestError((Exception) result);
}
else {
mResponseCallback.get().OnRequestError(new IOException("Unknown Error Contacting Host"));
}
mResponseCallback = null;
mProgressCallback = null;
}
}
}