Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileNotFoundException;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.os.Bundle;

public class Main {
    public static String simplePost(String url, Bundle params) throws MalformedURLException, IOException {
        return simplePost(url, params, "POST");
    }

    public static String simplePost(String url, Bundle params, String method)
            throws MalformedURLException, IOException {
        OutputStream os;

        System.setProperty("http.keepAlive", "false");
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " agent");

        conn.setRequestMethod(method);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        //conn.setRequestProperty("Connection", "Keep-Alive");

        conn.connect();

        os = new BufferedOutputStream(conn.getOutputStream());
        os.write(encodePostParams(params).getBytes());
        os.flush();

        String response = "";
        try {
            response = read(conn.getInputStream());
        } catch (FileNotFoundException e) {
            // Error Stream contains JSON that we can parse to a FB error
            response = read(conn.getErrorStream());
        }
        return response;
    }

    public static String encodePostParams(Bundle params) {

        StringBuilder sb = new StringBuilder();
        boolean and = true;
        for (String key : params.keySet()) {
            if (!and) {
                sb.append("&");
            }

            sb.append(key + "=" + params.getString(key));
            and = false;
        }

        return sb.toString();
    }

    public static String read(InputStream in) throws IOException {
        StringBuilder sb = new StringBuilder();
        BufferedReader r = new BufferedReader(new InputStreamReader(in), 1000);
        for (String line = r.readLine(); line != null; line = r.readLine()) {
            sb.append(line);
        }
        in.close();
        return sb.toString();
    }
}