Sunday 12 January 2020

Convert uri query parameters to a map of name, value

Below snippet takes a url and convert the query parameters to Map<String, String>.
public static Map<String, String> getQueryParamsMap(URL url) throws UnsupportedEncodingException {

 if (url == null) {
  return Collections.EMPTY_MAP;
 }

 // Get Query part of the url
 String queryPart = url.getQuery();

 if (queryPart == null || queryPart.isEmpty()) {
  return Collections.EMPTY_MAP;
 }

 Map<String, String> queryParams = new HashMap<String, String>();

 String[] pairs = queryPart.split("&");
 for (String pair : pairs) {
  String[] keyValuePair = pair.split("=");

  queryParams.put(URLDecoder.decode(keyValuePair[0], StandardCharsets.UTF_8.name()),
    URLDecoder.decode(keyValuePair[1], StandardCharsets.UTF_8.name()));
 }
 return queryParams;
}

App.java
package com.sample.app;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class App {

 public static Map<String, String> getQueryParamsMap(URL url) throws UnsupportedEncodingException {

  if (url == null) {
   return Collections.EMPTY_MAP;
  }

  // Get Query part of the url
  String queryPart = url.getQuery();

  if (queryPart == null || queryPart.isEmpty()) {
   return Collections.EMPTY_MAP;
  }

  Map<String, String> queryParams = new HashMap<String, String>();

  String[] pairs = queryPart.split("&");
  for (String pair : pairs) {
   String[] keyValuePair = pair.split("=");

   queryParams.put(URLDecoder.decode(keyValuePair[0], StandardCharsets.UTF_8.name()),
     URLDecoder.decode(keyValuePair[1], StandardCharsets.UTF_8.name()));
  }
  return queryParams;
 }

 public static void main(String args[]) throws MalformedURLException, UnsupportedEncodingException {

  String urlStr = "https://abc123.com/questions/?filter=age&page=112&pagesize=50";
  URL url = new URL(urlStr);

  Map<String, String> queryParamsMap = getQueryParamsMap(url);

  for (String key : queryParamsMap.keySet()) {
   System.out.println(key + " = " + queryParamsMap.get(key));
  }

 }

}

Output
filter = age
pagesize = 50
page = 112    


You may like

No comments:

Post a Comment