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.methods.HttpGet;

import org.apache.http.client.utils.URLEncodedUtils;
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.util.ArrayList;
import java.util.List;
import java.util.Map;

public class Main {
    public static String openGetConnection(String urlString, Map<String, String> map) {
        List<NameValuePair> nameValuePairs = new ArrayList<>();
        for (String key : map.keySet()) {
            nameValuePairs.add(new BasicNameValuePair(key, map.get(key)));
        }
        String params = URLEncodedUtils.format(nameValuePairs, "utf-8");
        urlString += "?";
        urlString += params;
        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(urlString);
        try {
            HttpResponse httpResponse = client.execute(get);
            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;
    }
}