Last active
August 29, 2015 14:07
-
-
Save arifsetiawan/9f34dbb9d859ec109de1 to your computer and use it in GitHub Desktop.
Simple Android AsyncTask
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// execute("GET","url","Body") | |
private class ApiClient extends AsyncTask<String, Void, String> { | |
// This runs in other thread | |
@Override | |
protected String doInBackground(String... params) { | |
String method = params[0]; | |
String url = params[1]; | |
String body = params[2]; | |
try { | |
InputStream is = null; | |
// Open connection | |
URL urlConn = new URL(url); | |
HttpURLConnection conn = (HttpURLConnection) urlConn.openConnection(); | |
// Set header | |
conn.setRequestMethod(method); | |
if(method.equalsIgnoreCase("POST")) { | |
conn.setRequestProperty("Content-Type", "application/json"); | |
} | |
conn.connect(); | |
// Add POST body | |
if(method.equalsIgnoreCase("POST")) { | |
byte[] outputBytes = body.getBytes("UTF-8"); | |
OutputStream os = conn.getOutputStream(); | |
os.write(outputBytes); | |
os.close(); | |
} | |
// Get response | |
int response = conn.getResponseCode(); | |
Log.d(TAG, "The response is: " + response); | |
is = conn.getInputStream(); | |
// Convert the InputStream into a string | |
String contentAsString = ""; | |
BufferedReader buffer = new BufferedReader(new InputStreamReader(is)); | |
String s = ""; | |
while ((s = buffer.readLine()) != null) { | |
contentAsString += s; | |
} | |
if (is != null) { | |
is.close(); | |
} | |
Log.d(TAG, "The content is: " + contentAsString); | |
return contentAsString; | |
} catch (IOException e) { | |
return "Unable to retrieve web page. URL may be invalid."; | |
} | |
} | |
@Override | |
protected void onPreExecute() { | |
setProgressBarIndeterminateVisibility(Boolean.TRUE); | |
} | |
// This runs in UI thread | |
@Override | |
protected void onPostExecute(String result) { | |
setProgressBarIndeterminateVisibility(Boolean.FALSE); | |
try { | |
JSONObject reader = new JSONObject(result); | |
// TODO :: Parse JSON here | |
} catch (JSONException e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment