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

import java.net.HttpURLConnection;

import java.net.URL;

import android.util.Log;

public class Main {
    static final String TAG = "SyncNetworkHelper";

    static public String download_json(String url_addr) {
        StringBuilder result = new StringBuilder();
        try {
            URL url = new URL(url_addr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            if (conn != null) {
                conn.setConnectTimeout(10000);
                conn.setUseCaches(false);
                if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    for (;;) {
                        String line = br.readLine();
                        if (line == null)
                            break;
                        result.append(line + '\n');
                    }
                    br.close();
                } else {
                    conn.disconnect();
                    return null;
                }
                conn.disconnect();
            }
        } catch (Exception e) {
            Log.e(TAG, e.toString());
            return null;
        }
        return result.toString();
    }
}