send HTTP Get Request - Android Network

Android examples for Network:HTTP Request

Description

send HTTP Get Request

Demo Code


//package com.java2s;

import java.net.HttpURLConnection;

import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class Main {

    public static URLConnection sendGetRequest(String url,
            Map<String, String> params, Map<String, String> headers)
            throws Exception {
        StringBuilder buf = new StringBuilder(url);
        Set<Entry<String, String>> entrys = null;

        if (params != null && !params.isEmpty()) {
            buf.append("?");
            entrys = params.entrySet();/*from  w w w.  jav a2s.co  m*/
            for (Map.Entry<String, String> entry : entrys) {
                buf.append(entry.getKey())
                        .append("=")
                        .append(URLEncoder.encode(entry.getValue(), "UTF-8"))
                        .append("&");
            }
            buf.deleteCharAt(buf.length() - 1);
        }
        URL url1 = new URL(buf.toString());
        HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
        conn.setRequestMethod("GET");
        // ?????
        if (headers != null && !headers.isEmpty()) {
            entrys = headers.entrySet();
            for (Map.Entry<String, String> entry : entrys) {
                conn.setRequestProperty(entry.getKey(), entry.getValue());
            }
        }
        conn.getResponseCode();
        return conn;
    }
}

Related Tutorials