Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

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

import java.io.InputStream;

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

public class Main {

    public static byte[] getBytes(String url) {
        try {
            URL u = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) u.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Charset", "UTF-8");
            InputStream is = connection.getInputStream();
            int contentLength = connection.getContentLength();
            byte[] data = new byte[contentLength];
            int alreadyRead = 0;
            int len = 0;
            while (alreadyRead < contentLength) {
                len = is.read(data, alreadyRead, contentLength - alreadyRead);
                alreadyRead += len;
            }
            is.close();
            return data;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }
}