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.ByteArrayOutputStream;

import java.io.InputStream;

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

public class Main {
    private static String AGENT = "Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:17.0) Gecko/17.0 Firefox/17.";

    public static String execUrl(String uri) {
        String res = "";
        try {
            URL url = new URL(uri);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("User-Agent", AGENT);

            res = readStream(conn.getInputStream());
        } catch (Exception e) {
            e.printStackTrace();
            res = "";
        }
        return res;
    }

    public static String readStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = -1;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        outStream.close();
        inStream.close();
        return outStream.toString();
    }
}