Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.io.IOException;

import java.util.ArrayList;

import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
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 android.util.Log;

public class Main {
    private static final String TAG = "HttpUtil";

    public static String postReqAsJsonAddParam(String uri, String requestJson, Map<String, String> param)
            throws ClientProtocolException, IOException {
        Log.i(TAG, "Send data to :" + uri + " ========== and the data str:" + requestJson);
        HttpPost post = new HttpPost(uri);
        List<NameValuePair> parameters = new ArrayList<NameValuePair>();
        for (Map.Entry<String, String> entry : param.entrySet()) {
            parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        parameters.add(new BasicNameValuePair("attendanceClientJSON", requestJson));
        post.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8"));
        HttpClient client = new DefaultHttpClient();
        HttpResponse response = client.execute(post);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String retStr = EntityUtils.toString(response.getEntity());
            Log.i(TAG, "=================response str:" + retStr);
            return retStr;
        }

        return response.getStatusLine().getStatusCode() + "ERROR";
    }
}