Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.util.HashMap;
import java.util.Map;
import org.apache.http.Header;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;

import org.apache.http.client.methods.HttpGet;

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.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;

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

    static public String doHttpGet(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);
        String result = "ERROR";
        if (null != map) {
            int i = 0;
            for (Map.Entry<String, String> entry : map.entrySet()) {

                if (i == 0) {
                    url = url + "?" + entry.getKey() + "=" + entry.getValue();
                } else {
                    url = url + "&" + entry.getKey() + "=" + entry.getValue();
                }

                i++;

            }
        }
        HttpGet get = new HttpGet(url);
        get.setHeaders(headers);
        try {

            HttpResponse response = client.execute(get);

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // setCookie(response);
                result = EntityUtils.toString(response.getEntity(), "UTF-8");

            } else {
                result = EntityUtils.toString(response.getEntity(), "UTF-8")
                        + response.getStatusLine().getStatusCode() + "ERROR";
            }
            if (result != null) {
                if (result.startsWith("\ufeff")) {
                    result = result.substring(1);
                }
            }

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

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

        }

        return result;
    }
}