Contenu connexe
Plus de Somenath Mukhopadhyay (20)
Generic asynchronous HTTP utility for android
- 1. SOM-ITSOLUTIONS
ANDROID
A generic HTTP Asynchronous Task
SOMENATH MUKHOPADHYAY
som-itsolutions
#A2 1/13 South Purbachal Hospital Road Kolkata 700078 Mob: +91 9748185282
Email: som@som-itsolutions.com / som.mukhopadhyay@gmail.com
Website:www.som-itsolutions.com
Blog: www.som-itsolutions.blogspot.com
- 2. Through this article i would like to share a generic HTTP Asynctask which can be used in
Android. It takes care of the Basic Authentication of a REST api. The code handles GET,
POST and PUT methods. The code is self explanatory and can be easily understood by a
programmer.
Class HTTPAsynctask
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import org.apache.http.NameValuePair;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
public class HTTPAsyncTask extends AsyncTask<String, Void, String> {
private CallBack mCb;
LinkedHashMap<Object, Object> mData = null;
//List mParams= new ArrayList();
LinkedHashMap<Object, Object> mParams = new LinkedHashMap<>();
List<NameValuePair> mPostDataList = new ArrayList<>();
String mTypeOfRequest;
String mStrToBeAppended = "?";
boolean isPostDataInJSONFormat = false;
boolean JSonAndData = false;
//JSONObject mJSONPostData = null;
String JSONStringData = null;
Context mContext = null;
public HTTPAsyncTask(Context context, CallBack c, HashMap<Object, Object>
data, String jsonString, String request) {
mContext = context;
mCb = c;
mTypeOfRequest = request;
JSONStringData = jsonString;
//Log.i("JSONDATA", mJSONPostData.toString());
if((data != null) && (jsonString == null)){
mData = (LinkedHashMap)data;
if(mTypeOfRequest.equalsIgnoreCase("GET")){
Object key = null;
Iterator<Object> it = mData.keySet().iterator();
while(it.hasNext()){
key = it.next();
mParams.put(key, mData.get(key));
- 3. Log.d("Data", key.toString() + " " +
mData.get(key).toString());
}
Iterator<Object>itParams = mParams.keySet().iterator();
int sizeOfParams = mParams.size();
int index = 0;
while(itParams.hasNext()){
Object keyParams = itParams.next();
index++;
if (index == sizeOfParams){
mStrToBeAppended+= keyParams + "=" +
mParams.get(keyParams);
break;
}
mStrToBeAppended+= keyParams + "=" +
mParams.get(keyParams)+ "&";
}
//add the last parameter without the "&"
//mStrToBeAppended+= "?" + key + "=" + mParams.get(key);
} //GET ENDS
if(mTypeOfRequest.equalsIgnoreCase("POST")){
Object key = null;
isPostDataInJSONFormat = false;
Iterator<Object> it = mData.keySet().iterator();
while(it.hasNext()){
key = it.next();
mParams.put(key, mData.get(key));
//mPostDataList.add(new
BasicNameValuePair(String(key),new String(mData.get(key)));
}
}
}
if((mData == null) && (JSONStringData == null)){
if(mTypeOfRequest == "GET"){
mStrToBeAppended = "";
}
}
if ((mData == null) && (JSONStringData != null) &&
(mTypeOfRequest.equalsIgnoreCase("POST") == true)){
isPostDataInJSONFormat = true;
}
}
@Override
- 4. protected String doInBackground(String... baseUrls) {
//android.os.Debug.waitForDebugger();
publishProgress(null);
if(mTypeOfRequest.equalsIgnoreCase("GET")){
String finalURL = baseUrls[0]+ mStrToBeAppended;
return HttpUtility.GET(finalURL);
}
if (mTypeOfRequest.equalsIgnoreCase("POST") ){
if(isPostDataInJSONFormat == false ){
if( JSonAndData == false){
mParams = null;
}
Log.i("NONJSONDATAPOSTMETHOd","Non-JSON POST method to
be called...");
return HttpUtility.POST(baseUrls[0],mParams );
}
if(isPostDataInJSONFormat == true){
Log.i("JSONDATAPOSTMETHOd","JSON POST method to be
called...");
return HttpUtility.POST(baseUrls[0], JSONStringData);
}
}
if (mTypeOfRequest.equalsIgnoreCase("PUT") ){
if(isPostDataInJSONFormat == false ){
if( JSonAndData == false){
mParams = null;
}
Log.i("NONJSONDATAPUTMETHOd","Non-JSON PUT method to be
called...");
return HttpUtility.PUT(baseUrls[0],mParams );
}
if(isPostDataInJSONFormat == true){
Log.i("JSONDATAPUTMETHOd","JSON PUT method to be
called...");
return HttpUtility.PUT(baseUrls[0], JSONStringData);
}
}
return null;
}
// onPostExecute displays the results of the AsyncTask.
@Override
- 5. protected void onPostExecute(String result) {
mCb.onResult(result);
}
@Override
protected void onProgressUpdate(Void...voids ) {
mCb.onProgress();
}
}
Class HttpUtility
import android.util.Base64;
import android.util.Log;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.StringTokenizer;
public class HttpUtility {
public final static String base_URL = "YOUR BASE URL";
private final static HttpClient mHhttpclient = new DefaultHttpClient();
public static String GET(String url){
Log.i("URL", url);
InputStream inputStream = null;
String result = "";
try {
- 6. HttpGet httpGet = new HttpGet(url);
// make GET request to the given URL
if(url.contains("@")){
String authStr = getTheBasicAuthStr(url);
String auth =new
String(Base64.encode(authStr.getBytes(),Base64.URL_SAFE|Base64.NO_WRAP));
httpGet.addHeader("Authorization", "Basic " + auth);
}
HttpResponse httpResponse = mHhttpclient.execute(httpGet);
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// convert inputstream to string
if(inputStream != null){
result = convertInputStreamToString(inputStream);
}
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
public static String POST(String url, LinkedHashMap<Object, Object> mParams){
InputStream inputStream = null;
String result = "";
try{
HttpPost post = new HttpPost(url);
if(url.contains("@")){
String authStr = getTheBasicAuthStr(url);
String auth =new
String(Base64.encode(authStr.getBytes(),Base64.URL_SAFE|Base64.NO_WRAP));
post.addHeader("Authorization", "Basic " + auth);
}
if(mParams != null){
post.setEntity(new UrlEncodedFormEntity((List<? extends
NameValuePair>) mParams, "UTF-8"));
}
HttpResponse httpResponse = mHhttpclient.execute(post);
// receive response as inputStream
- 7. inputStream = httpResponse.getEntity().getContent();
// convert inputstream to string
if(inputStream != null){
result = convertInputStreamToString(inputStream);
//inputStream.close();
}
else
result = "Did not work!";
}
catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
public static String POST(String url, String jsonString){
InputStream inputStream = null;
String result = "";
try{
HttpPost post = new HttpPost(url);
post.setHeader("Content-type", "application/json");
if(url.contains("@")){
String authStr = getTheBasicAuthStr(url);
String auth =new
String(Base64.encode(authStr.getBytes(),Base64.URL_SAFE|Base64.NO_WRAP));
post.addHeader("Authorization", "Basic " + auth);
}
//StringEntity se = new StringEntity(obj.toString());
StringEntity se = new StringEntity(jsonString);
//se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
post.setEntity(se);
HttpResponse httpResponse = mHhttpclient.execute(post);
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// convert inputstream to string
if(inputStream != null){
- 8. result = convertInputStreamToString(inputStream);
}
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
Log.i("JSONPOSTEND", "End of JSON data post methos...");
Log.i("JSONPOSTDATARESULT", result);
return result;
}
public static String PUT(String url, String jsonString){
InputStream inputStream = null;
String result = "";
try{
HttpPut put = new HttpPut(url);
put.setHeader("Content-type", "application/json");
if(url.contains("@")){
String authStr = getTheBasicAuthStr(url);
String auth =new
String(Base64.encode(authStr.getBytes(),Base64.URL_SAFE|Base64.NO_WRAP));
put.addHeader("Authorization", "Basic " + auth);
}
StringEntity se = new StringEntity(jsonString);
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
put.setEntity(se);
HttpResponse httpResponse = mHhttpclient.execute(put);
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// convert inputstream to string
if(inputStream != null){
result = convertInputStreamToString(inputStream);
}
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
- 9. Log.i("JSONPUTEND", "End of JSON data put methos...");
return result;
}
public static String PUT(String url, LinkedHashMap<Object, Object> mParams){
InputStream inputStream = null;
String result = "";
try{
HttpPut put = new HttpPut(url);
if(url.contains("@")){
String authStr = getTheBasicAuthStr(url);
String auth =new
String(Base64.encode(authStr.getBytes(),Base64.URL_SAFE|Base64.NO_WRAP));
put.addHeader("Authorization", "Basic " + auth);
}
HttpResponse httpResponse = mHhttpclient.execute(put);
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// convert inputstream to string
if(inputStream != null){
result = convertInputStreamToString(inputStream);
}
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
Log.i("JSONPUTEND", "End of JSON data put methos...");
return result;
}
public static String convertInputStreamToString(InputStream inputStream) throws
IOException{
BufferedReader bufferedReader = new BufferedReader( new
InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
- 10. inputStream.close();
return result;
}
public static String getTheBasicAuthStr(String url){
StringTokenizer tokenizer = new StringTokenizer(url, "@");
String firstHalf = tokenizer.nextToken();
String secondHalf = tokenizer.nextToken();
StringTokenizer tokenizer3 = new StringTokenizer(firstHalf,"//");
String temp = tokenizer3.nextToken();
String authStr = tokenizer3.nextToken();
return authStr;
}
}
The Asynctask can be called like the following (handles the basic authentication)
String url = "http://" + Id + ":"+ password + "@+URL”;
HTTPAsyncTask asyncTask = new HTTPAsyncTask(getApplicationContext(),c, null, null,
"PUT");
asyncTask.execute(url);
The Callback interface is as follows:
public interface CallBack {
public void onProgress();
public void onResult(String result);
public void onCancel();
}
And the Callback which will be implemented in an activity/fragment is as follows:
c = new CallBack() {
public void onProgress(){
if(mProgressDialog == null) {
mProgressDialog = new ProgressDialog(context);
mProgressDialog.setMessage("On Progress...");
mProgressDialog.setCancelable(true);
mProgressDialog.show();
}
- 11. }
public void onResult(String result){
mProgressDialog.dismiss();
if (!result.equals("") ) {
if (result.length() != 0){
//successful
}
else{
//unsuccessful
}
}
}
public void onCancel(){
Toast toast = Toast.makeText(getApplicationContext(), "Task
Cancelled", Toast.LENGTH_LONG);
toast.show();
if(mProgressDialog != null){
mProgressDialog.dismiss();
mProgressDialog = null;
}
}
};