Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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 java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

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

public class Main {
    public static String openPostConnection(String urlString, Map<String, String> map) {
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(urlString);
        List<NameValuePair> nameValuePairs = new ArrayList<>();
        for (String key : map.keySet()) {
            nameValuePairs.add(new BasicNameValuePair(key, map.get(key)));
        }
        try {
            post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            HttpResponse httpResponse = client.execute(post);
            BufferedReader br = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
            StringBuilder json = new StringBuilder("");
            String line = null;
            while ((line = br.readLine()) != null) {
                json.append(line);
            }
            return json.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}