Java HTTP Read getHtmlByteArray(final String url)

Here you can find the source of getHtmlByteArray(final String url)

Description

get Html Byte Array

License

Apache License

Declaration

public static byte[] getHtmlByteArray(final String url) 

Method Source Code


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

import java.io.ByteArrayOutputStream;

import java.io.IOException;
import java.io.InputStream;

import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class Main {
    public static byte[] getHtmlByteArray(final String url) {
        URL htmlUrl = null;/* w ww.jav  a 2  s  .c  o m*/
        InputStream inStream = null;
        try {
            htmlUrl = new URL(url);
            URLConnection connection = htmlUrl.openConnection();
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            int responseCode = httpConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                inStream = httpConnection.getInputStream();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] data = inputStreamToByte(inStream);

        return data;
    }

    public static byte[] inputStreamToByte(InputStream is) {
        try {
            ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
            int ch;
            while ((ch = is.read()) != -1) {
                bytestream.write(ch);
            }
            byte imgdata[] = bytestream.toByteArray();
            bytestream.close();
            return imgdata;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}

Related

  1. getContents(String urlStr)
  2. getContentTypeFromUrl(String urlname)
  3. getContentTypeSpecified(URLConnection connection)
  4. getContentWithPost(String urls, Map pv)
  5. getData(String urlString)
  6. getHtmlContent(String url)
  7. getInputStream(HttpURLConnection conn)
  8. getInputStream(HttpURLConnection connection)
  9. getInputStream(String myUrl)