Created
January 5, 2018 02:12
-
-
Save nguyenlinhnttu/e214aeb5359d0a550c24c1250e1462ec to your computer and use it in GitHub Desktop.
WebService AsyncTsk
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
| public interface OnTaskDoneListener { | |
| void onTaskDone(String responseData); | |
| void onError(); | |
| } |
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
| public class WebService extends AsyncTask<String, Void, String> { | |
| private Context mContext; | |
| private OnTaskDoneListener onTaskDoneListener; | |
| private String urlStr = ""; | |
| public WebService(Context context, String url, OnTaskDoneListener onTaskDoneListener) { | |
| this.mContext = context; | |
| this.urlStr = url; | |
| this.onTaskDoneListener = onTaskDoneListener; | |
| } | |
| @Override | |
| protected String doInBackground(String... params) { | |
| try { | |
| URL mUrl = new URL(urlStr); | |
| HttpURLConnection httpConnection = (HttpURLConnection) mUrl.openConnection(); | |
| httpConnection.setRequestMethod("GET"); | |
| httpConnection.setRequestProperty("Content-length", "0"); | |
| httpConnection.setUseCaches(false); | |
| httpConnection.setAllowUserInteraction(false); | |
| httpConnection.setConnectTimeout(100000); | |
| httpConnection.setReadTimeout(100000); | |
| httpConnection.connect(); | |
| int responseCode = httpConnection.getResponseCode(); | |
| if (responseCode == HttpURLConnection.HTTP_OK) { | |
| BufferedReader br = new BufferedReader(new InputStreamReader(httpConnection.getInputStream())); | |
| StringBuilder sb = new StringBuilder(); | |
| String line; | |
| while ((line = br.readLine()) != null) { | |
| sb.append(line + "\n"); | |
| } | |
| br.close(); | |
| return sb.toString(); | |
| } | |
| } catch (IOException e) { | |
| e.printStackTrace(); | |
| } catch (Exception ex) { | |
| ex.printStackTrace(); | |
| } | |
| return null; | |
| } | |
| @Override | |
| protected void onPostExecute(String s) { | |
| super.onPostExecute(s); | |
| if (onTaskDoneListener != null && s != null) { | |
| onTaskDoneListener.onTaskDone(s); | |
| } else | |
| onTaskDoneListener.onError(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment