Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import android.os.NetworkOnMainThreadException;
import android.util.Log;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class Main {
    private static final String CLASS_NAME = "RoskaUtil";

    public static final String postData(String url, HashMap<String, String> params) {
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        String outputString = null;

        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(params.size());
            Iterator it = params.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry pair = (Map.Entry) it.next();
                nameValuePairs.add(new BasicNameValuePair((String) pair.getKey(), (String) pair.getValue()));
                System.out.println(pair.getKey() + " = " + pair.getValue());
                it.remove(); // avoids a ConcurrentModificationException
            }
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);

            StatusLine statusLine = response.getStatusLine();
            if (statusLine.getStatusCode() == HttpURLConnection.HTTP_OK) {
                byte[] result = EntityUtils.toByteArray(response.getEntity());
                outputString = new String(result, "UTF-8");
            }

        } catch (ClientProtocolException e) {
            Log.i(CLASS_NAME, "Client protocolException happened: " + e.getMessage());
        } catch (IOException e) {
            Log.i(CLASS_NAME, "Client IOException happened: " + e.getMessage());
        } catch (NetworkOnMainThreadException e) {
            Log.i(CLASS_NAME, "Client NetworkOnMainThreadException happened: " + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            Log.i(CLASS_NAME, "Unknown exeception: " + e.getMessage());
        }
        return outputString;
    }

    public static final byte[] toByteArray(int value) {
        return ByteBuffer.allocate(4).putInt(value).array();
    }
}