Constructs an HttpURLConnection with the given request headers. - Android Network

Android examples for Network:HTTP Request

Description

Constructs an HttpURLConnection with the given request headers.

Demo Code


//package com.java2s;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class Main {
    /**//  w  ww.jav  a  2s.co  m
     * Constructs an {@link HttpURLConnection} with the given request headers.
     */
    public static HttpURLConnection get(URL url, Map<String, String> headers)
            throws IOException {
        HttpURLConnection c = (HttpURLConnection) url.openConnection();
        for (Map.Entry<String, String> h : headers.entrySet()) {
            c.addRequestProperty(h.getKey(), h.getValue());
        }
        return c;
    }

    /**
     * Constructs an {@link HttpURLConnection} with the specified settings, if non-null.
     */
    public static HttpURLConnection get(URL url, String accept,
            String auth, String eTag) throws IOException {
        Map<String, String> headers = new HashMap<>();
        if (accept != null) {
            headers.put("Accept", accept);
        }
        if (auth != null) {
            headers.put("Authorization", auth);
        }
        if (eTag != null) {
            headers.put("If-None-Match", eTag);
        }
        return get(url, headers);
    }
}

Related Tutorials