2017/03/21

Android 透過HttpURLConnection取得圖片

執行結果:





package com.cyfang.myapplication2;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ImageView;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    private ImageView imageView;
    private Thread thread;
    private URL url;


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

    private void init() {
        imageView = (ImageView) findViewById(R.id.imageView2);
        try {
            url = new URL("http://192.168.100.50/capture");
        } catch (MalformedURLException e) {
            Log.e("CY", e.getMessage());
        }
        thread = new Thread(runnable);
        thread.start();
    }

    private final Runnable runnable = new Runnable() {
        @Override
        public void run() {
            while (true)
                try {
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setDoInput(true);
                    connection.setRequestMethod("GET");
                    InputStream inputStream = connection.getInputStream();
                    final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    if (bitmap != null) {
                        imageView.post(new Runnable() {
                            @Override
                            public void run() {
                                imageView.setImageBitmap(bitmap);
                            }
                        });
                    }
                    inputStream.close();
                } catch (IOException e) {
                    Log.e("CY", e.getMessage());
                } catch (NullPointerException e) {
                    Log.e("CY", e.getMessage());
                }
        }
    };
}