HttpUtils { public static URL buildURL(final String hostName, final Map<String, String> query) { val escapedQuery = query.entrySet() .stream() .collect(Collectors.toMap( Map.Entry::getKey, e -> UrlEscapers.urlFormParameterEscaper().escape(e.getValue()) )); try { return new URL( hostName + (!hostName.endsWith("?") ? "?" : "") + Joiner.on("&").withKeyValueSeparator("=").join(escapedQuery) ); } catch (MalformedURLException e) { throw new IllegalArgumentException(e); } } private  HttpUtils(); static boolean isReachable(final String hostName, int port, int timeout); static URL buildURL(final String hostName, final Map<String, String> query);  }
@Test public void buildOfValidURLWithoutQuestionMarkOnEnd() throws Exception { val hostName = "http: val queryParams = new ImmutableMap.Builder<String, String>() .put("q", "test") .put("ref", "default") .put("json", "true") .build(); assertEquals(new URL("http: }
@Test public void buildOfValidURLWithQuestionMarkOnEnd() throws Exception { val hostName = "http: val queryParams = new ImmutableMap.Builder<String, String>() .put("q", "test") .put("ref", "default") .put("json", "true") .build(); assertEquals(new URL("http: }
@Test public void buildOfValidUrlWithEmptyQueryParams() throws Exception { val hostName = "http: Map<String, String> queryParams = Collections.emptyMap(); assertEquals(new URL("http: }
@Test public void buildOfValidURLWithEscapedCharactersInQuery() throws Exception { val hostName = "http: val queryParams = new ImmutableMap.Builder<String, String>() .put("q", "русский текст") .put("ref", "&f?$") .put("json", "true") .build(); val expected = new URL("http: + "+%D1%82%D0%B5%D0%BA%D1%81%D1%82" + "&ref=%26f%3F%24&json=true" ); assertEquals(expected, buildURL(hostName, queryParams)); }
@Test(expected = IllegalArgumentException.class) public void buildOfInvalidUrl() throws Exception { buildURL("sdsdsd", Collections.emptyMap()); }