Parse URI query string to Key Value

Parse URI query String to Map

  • 做 urlDecode 處理
  • 沒有任何 query String 回傳 Empty Map
  • 確保只處理 key-value 結構的 query String


package com.example.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.utils.URIBuilder;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

/**
 * Created by jerry on 2017/12/28.
 *
 * @author jerry
 */
@Slf4j
public class UriUtil {

    private UriUtil() {
    }

    public static Map splitQuery(final String uri) {

        Map queryPairs = new LinkedHashMap<>();

        try {
            final URI uri = new URIBuilder(uri).build();
            final String rawQuery = uri.getRawQuery();
            log.info("CurrentUrl Query: {}", rawQuery);

            // 過濾沒有 query string
            // 還有過濾無法成對 keyValue 的 query, e.g. http://host/path?123
            if (Objects.isNull(rawQuery) || !rawQuery.contains("=")) {
                return queryPairs;
            }
     
            final String[] pairs = rawQuery.split("&");

            final String utf8 = "UTF-8";

            for (String pair : pairs) {

                // 統一 decode
                final String deCodePair = URLDecoder.decode(pair, utf8);

                // check deCodePair 空字串,
                if (!deCodePair.isEmpty()) {
                    final String[] keyValue = pair.split("=");

                    // check is key value
                    if (2 == keyValue.length) {
                        final String key = keyValue[0];
                        final String value = keyValue[1];

                        queryPairs.put(key, value);
                    }
                }
            }

            log.info("Parser url: {} \n parameters: {}", url.toString(), queryPairs);
            return queryPairs;

        } catch (URISyntaxException uriBuilderUrlException) {
            uriBuilderUrlException.printStackTrace();
            log.warn("UriBuilder url ({}) has exception: {}", url, uriBuilderUrlException.getMessage());

        } catch (UnsupportedEncodingException urlDecodeException) {
            urlDecodeException.printStackTrace();
            log.warn("Decode url ({}) query has exception: {}", url, urlDecodeException.getMessage());
        }

        return queryPairs;
    }
}

沒有留言:

張貼留言