http Url Get from URL and parameter map - Android Network

Android examples for Network:URL

Description

http Url Get from URL and parameter map

Demo Code


//package com.java2s;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import java.util.Set;

public class Main {
    public static String httpUrlGet(String URL, Map<String, Object> map) {
        String result = "";
        // /*w w  w  .jav  a 2  s.c om*/
        String newURL = URL + "" + checkMap(map);
        try {
            // url
            URL url = new URL(newURL);
            // url
            HttpURLConnection conn = (HttpURLConnection) url
                    .openConnection();
            // get
            conn.setRequestMethod("GET");
            // 
            InputStream in = conn.getInputStream();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(in));
            // 
            if (conn.getResponseCode() == 200) {
                String line = "";
                while ((line = reader.readLine()) != null) {
                    // 
                    result += line;
                }
            } else {// 
                result = "";
            }
            // 
            in.close();
            // 
            conn.disconnect();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }

    private static String checkMap(Map<String, Object> map) {
        String data = "";
        Set<String> set = map.keySet();
        for (String key : set) {
            data = data + key + "=" + map.get(key) + "&";
        }
        data = data.substring(0, data.length() - 1);
        return data;
    }
}

Related Tutorials