Skip to content

Instantly share code, notes, and snippets.

@andhikayuana
Last active September 7, 2017 05:18
Show Gist options
  • Save andhikayuana/d033aa7d8d0243d892f8360caa3ba1ae to your computer and use it in GitHub Desktop.
Save andhikayuana/d033aa7d8d0243d892f8360caa3ba1ae to your computer and use it in GitHub Desktop.
AsyncTask POST form
package com.yyz;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
public class SubscribtionController extends AsyncTask < String, String, String > {
private HashMap<String, String> mData = null; // post data
private SubscriptionControllerListener mListener;
private static final String BASE_URL = "replace-with-yours-here";
public interface SubscriptionControllerListener {
void onSuccess(JSONObject jsonResponse);
void onError(Throwable throwable);
}
/**
* constructor
*/
public SubscribtionController(HashMap < String, String > data) {
mData = data;
}
public void setHandler(SubscriptionControllerListener listener) {
mListener = listener;
}
/**
* background
*/
@Override
protected String doInBackground(String...params) {
byte[] result = null;
String str;
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(BASE_URL + params[0]); // in this case, params[0]
// is URL
try {
// set up post data
ArrayList < NameValuePair > nameValuePair = new ArrayList < NameValuePair > ();
Iterator < String > it = mData.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
nameValuePair.add(new BasicNameValuePair(key, mData.get(key)));
}
post.setEntity(new UrlEncodedFormEntity(nameValuePair, "UTF-8"));
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpURLConnection.HTTP_OK) {
result = EntityUtils.toByteArray(response.getEntity());
str = new String(result, "UTF-8");
}
} catch (Exception e) {
mListener.onError(new SubscribtionException(e.getMessage()));
}
return str;
}
/**
* on getting result
*/
@Override
protected void onPostExecute(String result) {
if (result != null) {
try {
JSONObject response = new JSONObject(result);
if (response.getString("status").equals("success")) {
mListener.onSuccess(response);
} else {
SubscribtionException exception = new SubscribtionException(response.getString("status"));
exception.setResponse(response);
mListener.onError(exception);
}
} catch (Exception e) {
mListener.onError(new SubscribtionException(e.getMessage()));
}
} else {
mListener.onError(new SubscribtionException());
}
}
public class SubscribtionException extends RuntimeException {
private JSONObject mResponse = null;
public SubscribtionException(String msg) {
super(msg);
}
public SubscribtionException() {
super("Oops, something went wrong");
}
public void setResponse(JSONObject response) {
mResponse = response;
}
public JSONObject getResponse() {
return mResponse;
}
}
}
```
@andhikayuana
Copy link
Author

example use :

HashMap<String, String> data = new HashMap<String, String>();
data.put("username", "jarjit");
data.put("password", "jarjit");

SubscribtionController api = new SubscribtionController(data);
api.setHandler(new SubscriptionControllerListener() {
	@Override
	public void onSuccess(JSONObject jsonResponse) {
		// TODO Auto-generated method stub
	}
	
        @Override
	public void onError(Throwable throwable) {
		// TODO Auto-generated method stub
	}
});
api.execute("/v1/login");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment