UrlUtils { public static URI createUrl(String hostAndPath, String... keyValues) throws URISyntaxException { URI result = null; if (hostAndPath != null && keyValues != null && keyValues.length % 2 == 0) { StringBuilder r = new StringBuilder(); if (hostAndPath.startsWith("http:")) { r.append(hostAndPath.substring(5)); } else { r.append(hostAndPath); } boolean hasQuery = hostAndPath.matches(".+?.+=.+"); if (keyValues.length > 0 && !hasQuery) { r.append("?"); } for (int i = 0; i < keyValues.length - 1; i += 2) { if (keyValues[i] != null && keyValues[i + 1] != null) { if (i > 1 || hasQuery) { r.append("&"); } r.append(keyValues[i]).append("=").append(keyValues[i + 1]); } } result = new URI("http", r.toString(), null); } return result; } private  UrlUtils(); static URI createUrl(String hostAndPath, String... keyValues);  }
@Test public void testCreateUrl() throws URISyntaxException { URI uri = UrlUtils.createUrl("http: assertNotNull(uri); assertTrue(uri.toString().indexOf("%20") == 25); uri = UrlUtils.createUrl("http: assertNotNull(uri); assertTrue(uri.toString().indexOf("%20") == 26); uri = UrlUtils.createUrl(" assertNotNull(uri); assertTrue(uri.toString().indexOf("%20") == 26); uri = UrlUtils.createUrl(" assertNotNull(uri); assertTrue(uri.toString().indexOf("%20") == 26); }