HttpURLConnection的java URL编码
我写了一个代码从API调用中获取值。。。这是正常的网址工作正常,但当我编码的网址,然后使调用意味着它不工作。。。它给出了状态错误404
URL url = new URL(params[0]);
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
url = uri.toURL();
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestMethod("GET");
原始网址
https://staging.xyz.com/odata/Venues?$expand=Fixtures($filter=day(DateTime) eq 1 and month(DateTime) eq 12 and year(DateTime) eq 2018)&$filter=Fixtures/any(f: day(f/DateTime) eq 1 and month(f/DateTime) eq 12 and year(f/DateTime) eq 2018)
编码URL
http://staging.xyz.com/odata/Venues?$expand=Fixtures($filter=day(DateTime)%20eq%201%20and%20month(DateTime)%20eq%2012%20and%20year(DateTime)%20eq%202018)&$filter=Fixtures/any(f:%20day(f/DateTime)%20eq%201%20and%20month(f/DateTime)%20eq%2012%20and%20year(f/DateTime)%20eq%202018)
是否有办法使编码的URL正常工作
# 1 楼答案
URL可能包含的字符非常有限。唯一安全的字符是:
如果对其他字符进行编码,则可以将其包括在内,例如
(
如果编码为%28
,则可以将其包括在内某些字符必须根据用途进行编码,尤其是
?
、&
和=
。如果用于提供查询参数,则不得对其进行编码;如果它们是查询值的一部分,则必须对其进行编码因此,在构造查询部分之前必须进行编码:
URLEncoder.encode(queryValue)
分别对每个查询值进行编码李>query = "expand=" + encodedExpandValue + "&filter=" + encodedFilterValue
李>而且
/
字符是非常有问题的,不管它看起来是否经过编码。一些web服务器总是将其视为路径分隔符。最好在查询部分避免它# 2 楼答案
您可以使用
URLEncoder.encode(YOUR_URL)
对字符串URL单独的查询(以“&;分隔”)进行编码,然后最终将它们组合在一起或者,如果查询参数的键和值单独可用,则可以使用
Uri.parse
对整个URL进行编码,如下所示: