Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.io.BufferedInputStream;
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 android.util.Log;

public class Main {
    /**
     * Makes a GET call to the server.
     * @return The serve response (expected is JSON)
     */
    public static String httpGet(String urlStr) {
        try {
            URL url = new URL(urlStr);

            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());
            String r = readStream(in);
            urlConnection.disconnect();
            return r;
        } catch (MalformedURLException e) {
            Log.v("MyLog", "GET: Bad URL");
            e.printStackTrace();
            return "GET: Bad URL";
        } catch (IOException e) {
            Log.v("MyLog", "GET: Bad Con");
            e.printStackTrace();
            return "GET: Bad Con [" + urlStr + "]";
        }
    }

    private static String readStream(InputStream is) {
        try {
            ByteArrayOutputStream bo = new ByteArrayOutputStream();
            int i = is.read();
            while (i != -1) {
                bo.write(i);
                i = is.read();
            }
            return bo.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }
}