Java HTTP Get requestGetMethod(String url, String... params)

Here you can find the source of requestGetMethod(String url, String... params)

Description

Makes a GET method to an URL.

License

LGPL

Parameter

Parameter Description
url The URL to request.
params (Optional) All pairs "param=value" to use.

Exception

Parameter Description
MalformedURLException an exception
IOException an exception

Return

The response.

Declaration

public static String requestGetMethod(String url, String... params) throws MalformedURLException, IOException 

Method Source Code

//package com.java2s;
//License from project: LGPL 

import java.io.BufferedReader;

import java.io.IOException;
import java.io.InputStreamReader;

import java.io.UnsupportedEncodingException;

import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

public class Main {
    /**/*from   w  ww  . j  ava  2 s . c om*/
     * Makes a GET method to an URL.
     * @param url The URL to request.
     * @param params (Optional) All pairs "param=value" to use.
     * @return The response.
     * @throws MalformedURLException
     * @throws IOException 
     */
    public static String requestGetMethod(String url, String... params) throws MalformedURLException, IOException {
        url = encodeURLGET(url, params);
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setRequestMethod("GET");
        StringBuilder builder = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line).append('\n');
            }
        }
        return builder.toString();
    }

    /**
     * Transforms into an URL with GET query
     * @param url The url.
     * @param params (Optional) All pairs "param=value" to use.
     * @return The URL encoded.
     * @throws UnsupportedEncodingException 
     */
    public static String encodeURLGET(String url, String... params) throws UnsupportedEncodingException {
        if (params != null && params.length > 0) {
            String[] split = params[0].split("=");
            url += "?" + URLEncoder.encode(split[0], "utf-8") + "=" + URLEncoder.encode(split[1], "utf-8");
            for (int i = 1; i < params.length; i++) {
                split = params[i].split("=");
                url += "&" + URLEncoder.encode(split[0], "utf-8") + "=" + URLEncoder.encode(split[1], "utf-8");
            }
        }
        return url;
    }
}

Related

  1. readUrl(HttpURLConnection conn)
  2. readUrl(String url, String token)
  3. readURL(String url, String type)
  4. readUrl(String urlAsString, int timeout)
  5. readURL(URL url)