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.io.UnsupportedEncodingException;

import org.apache.http.HttpResponse;
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.protocol.HTTP;
import org.apache.http.util.EntityUtils;

public class Main {

    public static String getRepsonseString(String url, Map<String, String> params) {
        HttpPost request = new HttpPost(url);
        List<NameValuePair> p = new ArrayList<NameValuePair>();
        for (String key : params.keySet()) {
            p.add(new BasicNameValuePair(key, params.get(key)));
        }
        HttpClient httpClient = new DefaultHttpClient();
        String result = null;

        try {
            request.setEntity(new UrlEncodedFormEntity(p, HTTP.UTF_8));
            HttpResponse response = httpClient.execute(request);
            if (response.getStatusLine().getStatusCode() == 200) {
                result = new String(EntityUtils.toString(response.getEntity()).getBytes("ISO_8859_1"), "UTF-8");
            }
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (httpClient != null)
                httpClient.getConnectionManager().shutdown();
        }
        return result;
    }
}