Java URL Download get(String urlString)

Here you can find the source of get(String urlString)

Description

get

License

Apache License

Declaration

public static byte[] get(String urlString) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

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

public class Main {
    public static byte[] get(String urlString) {
        HttpURLConnection urlConnection = null;
        try {/*from  w ww .j  a  v  a 2  s  .co  m*/
            URL url = new URL(urlString);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setConnectTimeout(5000);
            urlConnection.setReadTimeout(3000);

            int responseCode = urlConnection.getResponseCode();
            if (responseCode == 200) {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                InputStream in = urlConnection.getInputStream();
                byte[] buffer = new byte[4 * 1024];
                int len = -1;
                while ((len = in.read(buffer)) != -1) {
                    bos.write(buffer, 0, len);
                }
                close(in);
                byte[] result = bos.toByteArray();
                close(bos);
                return result;
            }
        } catch (MalformedURLException e) {

        } catch (IOException e) {

        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }
        return null;
    }

    public static void close(Closeable stream) {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Related

  1. get(String url, int timeout, Map header)
  2. get(String url, Map headers)
  3. get(String url, Map params)
  4. get(String url, String encoding)
  5. get(String urlStr)
  6. get(URL host, String endpoint, String customer, String name, String version, OutputStream out)
  7. get(URL url)
  8. get(URL url, String acceptType)