Java tutorial
/** * Desciption: create Connection to server and return result string * Author: Tran Quang Long * Create date: Feb 25, 2014 */ package longism.com.api; import android.app.Activity; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; 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.HttpUriRequest; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; import java.io.File; import java.io.InputStream; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; import java.util.Set; /** * Desciption: Use for connect to sever and return string of JSONOBJECT * * @tutorial: - if you need to upload file to sever, you need to import libraries: * - httpclient-cache-4.3.5.jar,httpcore-4.3.2.jar and httpmime-4.3.5.jar * - if you don't upload file to sever, you can delete function loadJSONWithUploadFile, and don't need to import libraries above * - if you see error: Error:duplicate files during packaging of APK ..\app\build\outputs\apk\app-debug-unaligned.apk * - you must put this code into android {} in your build.grade: packagingOptions {exclude 'META-INF/DEPENDENCIES'exclude 'META-INF/NOTICE'exclude 'META-INF/LICENSE'} * @author: Nguyen Long Create date: July 08, 2015 */ public class APIUtils { public static int TIMEOUT_TIME = 30000; /** * define action to do */ public static final int ACTION_GET_JSON = 1; public static final int ACTION_POST_JSON = 2; public static final int ACTION_GET_JSON_WITH_AUTH = 3; public static final int ACTION_POST_JSON_WITH_AUTH = 4; public static final int ACTION_UPLOAD = 5; public static final int ACTION_UPLOAD_WITH_AUTH = 6; /** * TODO Function: Load json by type GET.<br> * * @param activity * @param data * @param url * @param apiCallBack * @date: July 07, 2015 * @author: Nguyen Long */ public static void LoadGETJSON(final Activity activity, final HashMap<String, String> data, final String url, final APICallBack apiCallBack) { LoadJSONByType(activity, ACTION_GET_JSON, data, url, "", "", apiCallBack); } /** * TODO Function: Load json by type POST.<br> * * @param activity * @param data * @param url * @param apiCallBack * @date: July 07, 2015 * @author: Nguyen Long */ public static void LoadPOSTJSON(final Activity activity, final HashMap<String, String> data, final String url, final APICallBack apiCallBack) { LoadJSONByType(activity, ACTION_POST_JSON, data, url, "", "", apiCallBack); } /** * TODO Function: Log in then load json by type GET.<br> * * @param activity * @param data * @param url * @param apiCallBack * @date: July 07, 2015 * @author: Nguyen Long */ public static void LoadGetJSONWithAuth(final Activity activity, final HashMap<String, String> data, final String url, final APICallBack apiCallBack, final String sUserName, final String sUserPassword) { LoadJSONByType(activity, ACTION_GET_JSON_WITH_AUTH, data, url, sUserName, sUserPassword, apiCallBack); } /** * TODO Function: Log in then load json by type POST.<br> * * @param activity * @param data * @param url * @param apiCallBack * @date: July 07, 2015 * @author: Nguyen Long */ public static void LoadPOSTJSONWithAuth(final Activity activity, final HashMap<String, String> data, final String url, final APICallBack apiCallBack, final String sUserName, final String sUserPassword) { LoadJSONByType(activity, ACTION_POST_JSON_WITH_AUTH, data, url, sUserName, sUserPassword, apiCallBack); } /** * TODO Function:load json with upload file.<br> * * @param activity * @param data * @param files * @param url * @param apiCallBack * @date: July 07, 2015 * @author: Nguyen Long */ public static void LoadJSONWithUpLoad(final Activity activity, final HashMap<String, String> data, final HashMap<String, String> files, final String url, final APICallBack apiCallBack) { loadJSONWithUploadFile(activity, ACTION_UPLOAD, data, files, url, "", "", apiCallBack); } /** * TODO Function: Authenticate then load json with upload file.<br> * * @param activity * @param data * @param files * @param url * @param apiCallBack * @date: July 07, 2015 * @author: Nguyen Long */ public static void LoadJSONWithUPLoadAndAuth(final Activity activity, final HashMap<String, String> data, final HashMap<String, String> files, final String url, final String sUserName, final String sUserPassword, final APICallBack apiCallBack) { loadJSONWithUploadFile(activity, ACTION_UPLOAD_WITH_AUTH, data, files, url, sUserName, sUserPassword, apiCallBack); } /** * TODO Function:Load json by type.<br> * * @param activity - to get context * @param action - get or post or s.thing else. Define at top of class * @param data - Parameter * @param url - host of API * @param apiCallBack - call back to handle action when start, finish, success or fail * @param username - username if sever need to log in * @param password - password if sever need to log in * @date: July 07, 2015 * @author: Nguyen Long */ public static void LoadJSONByType(final Activity activity, final int action, final HashMap<String, String> data, final String url, final String username, final String password, final APICallBack apiCallBack) { activity.runOnUiThread(new Runnable() { @Override public void run() { apiCallBack.uiStart(); } }); new Thread(new Runnable() { @Override public synchronized void run() { try { HttpGet get = null; HttpPost post = null; HttpResponse response = null; String paramString = null; ArrayList<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>(); if (data != null) { Set<String> set = data.keySet(); for (String key : set) { BasicNameValuePair value = new BasicNameValuePair(key, data.get(key)); list.add(value); } } HttpParams params = new BasicHttpParams(); HttpConnectionParams.setSoTimeout(params, TIMEOUT_TIME); HttpConnectionParams.setConnectionTimeout(params, TIMEOUT_TIME); DefaultHttpClient client = new DefaultHttpClient(params); /** * Select action to do */ switch (action) { case ACTION_GET_JSON: paramString = URLEncodedUtils.format(list, "utf-8"); get = new HttpGet(url + "?" + paramString); response = client.execute(get); break; case ACTION_POST_JSON: post = new HttpPost(url); post.setEntity(new UrlEncodedFormEntity(list, "UTF-8")); response = client.execute(post); break; case ACTION_GET_JSON_WITH_AUTH: paramString = URLEncodedUtils.format(list, "utf-8"); get = new HttpGet(url + "?" + paramString); setAuthenticate(client, get, username, password); response = client.execute(get); break; case ACTION_POST_JSON_WITH_AUTH: post = new HttpPost(url); post.setEntity(new UrlEncodedFormEntity(list, "UTF-8")); setAuthenticate(client, post, username, password); response = client.execute(post); break; } final StringBuilder builder = new StringBuilder(); if (response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { InputStream inputStream = response.getEntity().getContent(); Scanner scanner = new Scanner(inputStream); while (scanner.hasNext()) { builder.append(scanner.nextLine()); } inputStream.close(); scanner.close(); apiCallBack.success(builder.toString(), 0); } else { apiCallBack.fail(response != null && response.getStatusLine() != null ? "response null" : "" + response.getStatusLine().getStatusCode()); } } catch (final Exception e) { apiCallBack.fail(e.getMessage()); } finally { activity.runOnUiThread(new Runnable() { @Override public void run() { apiCallBack.uiEnd(); } }); } } }).start(); } /** * TODO Function:Upload file then Load json by type POST.<br> * * @param activity - to get context * @param action - need authenticate or not, define at top of class * @param data - parameter String * @param files - param file input <key,path of file> * @param url - host of API * @param apiCallBack - call back to handle action when start, finish, success or fail * @date: July 07, 2015 * @author: Nguyen Long */ public static void loadJSONWithUploadFile(final Activity activity, final int action, final HashMap<String, String> data, final HashMap<String, String> files, final String url, final String sUserName, final String sUserPassword, final APICallBack apiCallBack) { activity.runOnUiThread(new Runnable() { @Override public void run() { apiCallBack.uiStart(); } }); new Thread(new Runnable() { @Override public synchronized void run() { try { HttpParams params = new BasicHttpParams(); HttpConnectionParams.setSoTimeout(params, TIMEOUT_TIME); HttpConnectionParams.setConnectionTimeout(params, TIMEOUT_TIME); Charset chars = Charset.forName("UTF-8"); DefaultHttpClient client = new DefaultHttpClient(params); HttpPost post = new HttpPost(url); // DLog.e("Accountant", "url : " + url); MultipartEntity multipartEntity = new MultipartEntity(); if (files != null) { Set<String> set = files.keySet(); for (String key : set) { // DLog.e("Accountant", "param : " + key); File file = new File(files.get(key)); multipartEntity.addPart(key, new FileBody(file)); } } if (data != null) { Set<String> set = data.keySet(); for (String key : set) { // DLog.e("Accountant", "param : " + key); StringBody stringBody = new StringBody(data.get(key), chars); multipartEntity.addPart(key, stringBody); } } post.setEntity(multipartEntity); /** * if need authen then run this code below */ if (action == ACTION_UPLOAD_WITH_AUTH) { setAuthenticate(client, post, sUserName, sUserPassword); } HttpResponse response = null; response = client.execute(post); final StringBuilder builder = new StringBuilder(); if (response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { InputStream inputStream = response.getEntity().getContent(); Scanner scanner = new Scanner(inputStream); while (scanner.hasNext()) { builder.append(scanner.nextLine()); } inputStream.close(); scanner.close(); apiCallBack.success(builder.toString(), 0); } else { apiCallBack.fail(response != null && response.getStatusLine() != null ? "response null" : "" + response.getStatusLine().getStatusCode()); } } catch (final Exception e) { apiCallBack.fail(e.getMessage()); } finally { activity.runOnUiThread(new Runnable() { @Override public void run() { apiCallBack.uiEnd(); } }); } } }).start(); } /** * TODO Function: Authenticate, login to sever<br> * * @param httpClient * @param httpRequest * @param userName * @param password * @date: July 07, 2015 * @author: Nguyen Long */ public static void setAuthenticate(DefaultHttpClient httpClient, HttpUriRequest httpRequest, String userName, String password) { UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userName, password); AuthScope scope = new AuthScope(httpRequest.getURI().getHost(), httpRequest.getURI().getPort()); httpClient.getCredentialsProvider().setCredentials(scope, credentials); } /** * TODO Function: check network connected, * * @param activity * @return true if Network is connected * @require: android.Manifest.permission.ACCESS_NETWORK_STATE * @author: Nguyen Long * @date: July 08, 2016 */ public static boolean isNetworkConnected(Activity activity) { try { ConnectivityManager cm = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (netInfo != null && netInfo.isConnected()) { return true; } return false; } catch (Exception e) { return false; } } }