package binaron.com.httpexample;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.ImageView;

import java.net.HttpURLConnection;
import java.net.URL;


import javax.net.ssl.HttpsURLConnection;

public class MainActivity extends Activity {

    public static final String TAG = "MainActivity";

    Handler uiHandler;
    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        uiHandler = new Handler();
        imageView = (ImageView) findViewById(R.id.imageView);

        Thread httpThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // wait for 3 seconds
                    Thread.sleep(3000);

                    URL url = new URL("http://www.droidheros.com/wp-content/uploads/2014/01/Android-apps-for-bodybuilders1.png");
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    // Timeout for reading InputStream arbitrarily set to 3000ms.
                    connection.setReadTimeout(3000);
                    // Timeout for connection.connect() arbitrarily set to 3000ms.
                    connection.setConnectTimeout(3000);
                    // For this use case, set HTTP method to GET.
                    connection.setRequestMethod("GET");
                    // Already true by default but setting just in case; needs to be true since this request
                    // is carrying an input (response) body.
                    connection.setDoInput(true);
                    // Open communications link (network traffic occurs here).
                    connection.connect();

                    int responseCode = connection.getResponseCode();
                    if (responseCode != HttpsURLConnection.HTTP_OK) {
                        Log.d(TAG, "HTTP connection error");
                    }
                    final Bitmap bmp = BitmapFactory.decodeStream(connection.getInputStream());
                    connection.disconnect();

                    uiHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            imageView.setImageBitmap(bmp);
                        }
                    });
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        httpThread.start();
    }
}
