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 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 postReqAsJson(String uri, String requestJson) 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>();
        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";
    }
}