Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.io.ByteArrayOutputStream;

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

import java.net.URL;

import android.util.Log;

public class Main {
    private final static String LOG_TAG = "com.kowd.pcapp.client.android.util.PCHelper";

    public static byte[] downloadImage(final URL url) {
        InputStream in = null;
        int responseCode = -1;

        try {
            final HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setDoInput(true);
            con.connect();
            responseCode = con.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                in = con.getInputStream();
                return getByteFromInputStream(in);
            }
        } catch (final IOException e) {
            Log.e(LOG_TAG, "Failed to download image from: " + url.toString(), e);
        }
        return null;
    }

    public static byte[] getByteFromInputStream(final InputStream in) throws IOException {
        ByteArrayOutputStream buffer = null;
        buffer = new ByteArrayOutputStream();
        int nRead;
        final byte[] data = new byte[16384];

        while ((nRead = in.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, nRead);
        }

        buffer.flush();

        return buffer.toByteArray();
    }
}