build Get Url with parameter - Android Network

Android examples for Network:URL

Description

build Get Url with parameter

Demo Code


//package com.java2s;

import java.io.IOException;

import java.io.UnsupportedEncodingException;

import java.net.URL;

import java.net.URLEncoder;

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

import java.util.Set;

import android.text.TextUtils;

public class Main {
    public static final String DEFAULT_CHARSET = "UTF-8";

    public static URL buildGetUrl(String url, Map<String, String> params,
            String charset) throws IOException {
        String queryString = buildQuery(params, charset);
        return buildGetUrl(url, queryString);
    }//from   w w w . ja  v  a 2  s  . c  o m

    private static URL buildGetUrl(String strUrl, String query)
            throws IOException {
        URL url = new URL(strUrl);
        if (TextUtils.isEmpty(query)) {
            return url;
        }

        if (TextUtils.isEmpty(url.getQuery())) {
            if (strUrl.endsWith("?")) {
                strUrl = strUrl + query;
            } else {
                strUrl = strUrl + "?" + query;
            }
        } else {
            if (strUrl.endsWith("&")) {
                strUrl = strUrl + query;
            } else {
                strUrl = strUrl + "&" + query;
            }
        }

        return new URL(strUrl);
    }

    public static String buildQuery(Map<String, String> params,
            String charset) throws UnsupportedEncodingException {
        if (params == null || params.isEmpty()) {
            return null;
        }
        if (TextUtils.isEmpty(charset)) {
            charset = DEFAULT_CHARSET;
        }

        StringBuilder query = new StringBuilder();
        Set<Entry<String, String>> entries = params.entrySet();
        boolean hasParam = false;

        for (Entry<String, String> entry : entries) {
            String name = entry.getKey();
            String value = entry.getValue();
            if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(value)) {
                if (hasParam) {
                    query.append("&");
                } else {
                    hasParam = true;
                }

                query.append(name).append("=")
                        .append(URLEncoder.encode(value, charset));
            }
        }

        return query.toString();
    }

    public static String encode(String value) {
        return encode(value, DEFAULT_CHARSET);
    }

    public static String encode(String value, String charset) {
        String result = null;
        if (!TextUtils.isEmpty(value)) {
            try {
                result = URLEncoder.encode(value, charset);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return result;
    }
}

Related Tutorials