简体   繁体   中英

Adding commas to java.net.URL

I am trying to run a query on Elasticsearch's /_cluster endpoint.

I would like to do the following:

https://<my cluster>/_cluster/state/version,master

However, when I am getting a 403 response code.

Previously, I was using this logic to encode the string:

URL url = new URL(String.format(%s, %s, "myendpoint", "/_cluster/state/version,master"));

That did not work.

This also did not work:

url = new URI(String.format("%s%s", "myendpoint", "/_cluster/state/version,master", null)).toURL();

Is there a proper way to add commas to a java.net.URI?

EDIT: There were no problems with the URL. For example, this would work:

        URL url = new URL(String.format("%s", " http://localhost:9200/_cluster/state/version%5C%2Cnodes"));

        conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(30000);
        conn.setReadTimeout(30000);

I had some proprietary signing code that was adding connection properties that was causing this to fail.

您需要使用转义来构建URL.comma =%2C

I think this works to you:

final String ENCODING = "UTF-8";


String queryString = 
        "a=" + URLEncoder.encode("Frick&Frack", ENCODING) +
        "&b=" + URLEncoder.encode("New York", ENCODING) +
        "&c=" + URLEncoder.encode("US/Eastern", ENCODING) +
        "&d=" + URLEncoder.encode("when?", ENCODING) +
        "&e=" + URLEncoder.encode("20%", ENCODING) +
        "&f=" + URLEncoder.encode("#1", ENCODING);

URI uri = new URI("http", null, "example.com", -1, "/accounts", queryString, null);

System.out.println(uri);

Set encoding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM