Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.io.BufferedReader;

import java.io.InputStream;
import java.io.InputStreamReader;

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

public class Main {
    public static String SimpleHttp(String urlStr) throws Exception {

        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        int resCode = conn.getResponseCode();
        InputStream input = null;
        String result = null;
        if (resCode == 200) {
            input = conn.getInputStream();
            result = toString(input);
            input.close();
            conn.disconnect();
        } else {
            throw new Exception("connect failed");
        }

        return result;
    }

    private static String toString(InputStream input) {

        String content = null;
        try {
            InputStreamReader ir = new InputStreamReader(input);
            BufferedReader br = new BufferedReader(ir);

            StringBuilder sbuff = new StringBuilder();
            while (null != br) {
                String temp = br.readLine();
                if (null == temp)
                    break;
                sbuff.append(temp).append(System.getProperty("line.separator"));
            }

            content = sbuff.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return content;
    }
}