build URL Query - Android Network

Android examples for Network:URL

Description

build URL Query

Demo Code


//package com.java2s;

import java.io.IOException;

import java.io.UnsupportedEncodingException;

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 String buildQuery(Map<String, String> params,
            String charset) throws UnsupportedEncodingException {
        if (params == null || params.isEmpty()) {
            return null;
        }/* w w  w  . j  a v a 2s.com*/
        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