Change query string in JAVA
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; public class MyURLClass { public String addOrChangeQuery(String mainUrl, String key, String newValue) throws MalformedURLException, UnsupportedEncodingException { int queryStart = mainUrl.indexOf('?'); String newUrl; if (queryStart == -1) { newUrl = mainUrl + "?" + getNewQuery(null, key, newValue); } else { newUrl = mainUrl.substring(0, queryStart) + "?" + getNewQuery(mainUrl.substring(queryStart + 1), key, newValue); } return newUrl; } private String getNewQuery(String query, String key, String newValue) throws UnsupportedEncodingException { Map<String, String> map = new HashMap<>(); if (query == null) { map.put(key, newValue); } else { String[] params = query.split("&"); Boolean isKey = false; for (String param : params) { String queryName = param.split("=")[0]; String queryValue = param.split("=")[1]; if (queryName.equalsIgnoreCase(key)) { isKey = true; queryValue = newValue; } map.put(queryName, queryValue); } if (!isKey) { map.put(key, newValue); } } StringBuilder sb = new StringBuilder(); for (HashMap.Entry<String, String> e : map.entrySet()) { if (sb.length() > 0) { sb.append('&'); } sb.append(URLEncoder.encode(e.getKey(), "UTF-8")).append('=').append(URLEncoder.encode(e.getValue(), "UTF-8")); } return sb.toString(); } private Map<String, String> getQueryMap(String query) { Map<String, String> map = new HashMap<>(); String[] params = query.split("&"); for (String param : params) { String queryName = param.split("=")[0]; String queryValue = param.split("=")[1]; map.put(queryName, queryValue); } return map; } } |