Construct and return an HttpURLConnection object to use for a GET connection. - Android Network

Android examples for Network:HTTP Get

Description

Construct and return an HttpURLConnection object to use for a GET connection.

Demo Code


//package com.java2s;

import java.io.IOException;

import java.net.HttpURLConnection;
import java.net.URL;

public class Main {
    /**/*from   w  w  w. ja  v  a2s  . c o  m*/
     * Construct and return an <code>HttpURLConnection</code> object
     * to use for a GET connection.
     * @param baseUrl The base URL of the server
     * @param path The path to make the GET call to.
     * @param cookie The cookie to send to the server (null if no cookie)
     * @return an <code>HttpURLConnection</code> object representing the established connection
     * @throws IOException if there was trouble establishing the connection
     */
    public static HttpURLConnection makeGet(URL baseUrl, String path,
            String cookie) throws IOException {
        URL url = new URL(String.format("%s%s", baseUrl.toString(), path));
        HttpURLConnection connection = (HttpURLConnection) url
                .openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Content-Language", "en-US");

        // Set cookie if it was given
        if (cookie != null) {
            connection.setRequestProperty("Cookie", cookie);
        }

        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(false);

        return connection;
    }
}

Related Tutorials