Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import android.util.Log;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import java.util.zip.GZIPInputStream;

public class Main {
    private static String KEY_LOG = null;

    public static String stringFromHttpPost(String urlStr, String body) {
        HttpURLConnection conn;
        try {
            URL e = new URL(urlStr);
            conn = (HttpURLConnection) e.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setInstanceFollowRedirects(true);
            conn.setRequestMethod("POST");
            OutputStream os1 = conn.getOutputStream();
            DataOutputStream out1 = new DataOutputStream(os1);
            out1.write(body.getBytes("UTF-8"));
            out1.flush();
            conn.connect();
            String line;
            BufferedReader reader;
            StringBuffer sb = new StringBuffer();
            if ("gzip".equals(conn.getHeaderField("Content-Encoding"))) {
                reader = new BufferedReader(
                        new InputStreamReader(new GZIPInputStream(conn.getInputStream()), "UTF-8"));
            } else {
                reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            }
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            logError(e.getMessage());
        }
        return null;
    }

    public static void logError(String error) {
        Log.e(KEY_LOG, error);
    }
}