Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;

import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;

public class Main {
    private static Header[] headers = new BasicHeader[1];
    private static int TIMEOUT = 5 * 1000;

    /**
     * Op Http post request , "404error" response if failed
     * 
     * @param url
     * @param map
     *            Values to request
     * @return
     */

    static public String doHttpPost(String url, HashMap<String, String> map) {

        HttpClient client = new DefaultHttpClient();
        HttpConnectionParams.setConnectionTimeout(client.getParams(), TIMEOUT);
        HttpConnectionParams.setSoTimeout(client.getParams(), TIMEOUT);
        ConnManagerParams.setTimeout(client.getParams(), TIMEOUT);
        HttpPost post = new HttpPost(url);
        post.setHeaders(headers);
        String result = "ERROR";
        ArrayList<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
        if (map != null) {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                BasicNameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue());
                pairList.add(pair);
            }

        }
        try {
            HttpEntity entity = new UrlEncodedFormEntity(pairList, "UTF-8");
            post.setEntity(entity);
            HttpResponse response = client.execute(post);

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

                result = EntityUtils.toString(response.getEntity(), "UTF-8");

            } else {
                result = EntityUtils.toString(response.getEntity(), "UTF-8")
                        + response.getStatusLine().getStatusCode() + "ERROR";
            }

        } catch (ConnectTimeoutException e) {
            result = "TIMEOUTERROR";
        }

        catch (Exception e) {
            result = "OTHERERROR";
            e.printStackTrace();

        }
        return result;
    }
}