Advertisement
thibthibaut

HTTP GET REQUEST

Oct 12th, 2015
269
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.17 KB | None | 0 0
  1. package com.example.thibaut.tp1;
  2.  
  3. import android.app.Activity;
  4. import android.os.AsyncTask;
  5. import android.util.Log;
  6. import android.widget.EditText;
  7.  
  8. import org.json.JSONException;
  9. import org.json.JSONObject;
  10.  
  11. import java.io.BufferedInputStream;
  12. import java.io.BufferedReader;
  13. import java.io.IOException;
  14. import java.io.InputStream;
  15. import java.io.InputStreamReader;
  16. import java.net.HttpURLConnection;
  17. import java.net.URL;
  18.  
  19.  
  20. /**
  21.  * Created by thibaut on 08/10/2015.
  22.  */
  23. class JSONAsyncTask extends AsyncTask<String, String, String> {
  24.  
  25.  
  26.     Activity mActivity;
  27.     EditText out;
  28.  
  29.     public JSONAsyncTask(Activity a) {
  30.         this.mActivity = a;
  31.     }
  32.  
  33.  
  34.     @Override
  35.     protected void onPreExecute() {
  36.         super.onPreExecute();
  37.  
  38.     }
  39.  
  40.     @Override
  41.     protected String doInBackground(String... args) {
  42.  
  43.         StringBuilder result = new StringBuilder();
  44.  
  45.         HttpURLConnection urlConnection = null;
  46.  
  47.  
  48.         try {
  49.             URL url = new URL("http://api.fixer.io/latest?base=USD&symbols=EUR");
  50.             urlConnection = (HttpURLConnection) url.openConnection();
  51.             InputStream in = new BufferedInputStream(urlConnection.getInputStream());
  52.  
  53.             BufferedReader reader = new BufferedReader(new InputStreamReader(in));
  54.  
  55.             String line;
  56.             while ((line = reader.readLine()) != null) {
  57.                 result.append(line);
  58.             }
  59.  
  60.         }catch( Exception e) {
  61.             e.printStackTrace();
  62.         }
  63.         finally {
  64.             assert urlConnection != null;
  65.             urlConnection.disconnect();
  66.         }
  67.  
  68.  
  69.         return result.toString();
  70.     }
  71.  
  72.  
  73.     protected void onPostExecute(String result) {
  74.  
  75.  
  76.         try {
  77.             JSONObject data = new JSONObject(result);
  78.  
  79.             String tx = data.getString("rates");
  80.  
  81.             JSONObject currency = new JSONObject(tx);
  82.  
  83.             double value = currency.getDouble("EUR");
  84.  
  85.  
  86.             out = (EditText)
  87.                 mActivity.findViewById(R.id.output_value);
  88.  
  89.             out.setText( Double.toString(value) );
  90.  
  91.         } catch (JSONException e) {
  92.             e.printStackTrace();
  93.         }
  94.  
  95.  
  96.  
  97.  
  98.  
  99.     }
  100. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement