Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //--- REMEMBER TO ADD PERMISSION (android.permission.INTERNET) TO ANDROID MANIFEST !!! ---//
- // Background task class
- public class HttpGetTask extends AsyncTask<String, Void, String> {
- interface OnHttpGetListener {
- public void httpGetCompleted(String response);
- public void httpGetFailed(String error);
- }
- private OnHttpGetListener mListener;
- private boolean mGetFailed;
- public HttpGetTask(OnHttpGetListener listener) {
- mListener = listener;
- }
- @Override
- protected String doInBackground(String... params) {
- try {
- HttpGet uri = new HttpGet(params[0]);
- DefaultHttpClient client = new DefaultHttpClient();
- HttpResponse resp = client.execute(uri);
- StatusLine status = resp.getStatusLine();
- if( status.getStatusCode() == 200 ) {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- resp.getEntity().writeTo(out);
- out.close();
- return out.toString();
- } else {
- throw new IllegalArgumentException("Status code was not 200");
- }
- }
- catch (Exception e) {
- mGetFailed = true;
- return e.getMessage();
- }
- }
- @Override
- protected void onPostExecute(String response) {
- if(mGetFailed) {
- mListener.httpGetFailed(response);
- } else {
- mListener.httpGetCompleted(response);
- }
- }
- }
- //-----------------------------------------------------------------//
- // Exaple how to use that
- public class MainActivity extends Activity implements OnHttpGetListener {
- public static final String TAG = "myApp";
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- getJSON();
- }
- private void getJSON() {
- HttpGetTask jsonGetter = new HttpGetTask(this); // Registers MainActivity to listen callbacks
- final String jsonUrl = // url to json
- jsonGetter.execute(jsonUrl); // Starts the async task
- }
- // Callbacks from the async task
- @Override
- public void httpGetCompleted(String response) {
- // This gets called when the background task
- // to get json is completed without errors
- Toast.makeText(this, "Response: " + response, Toast.LENGTH_SHORT).show();
- Log.d(TAG, response); // printing to debug
- }
- @Override
- public void httpGetFailed(String error) {
- // This gets called when the background task failes to get json
- Toast.makeText(this, "Http get failed!", Toast.LENGTH_SHORT).show();
- Log.e(TAG, error); // printing to error
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement