java - HttpURLConnection 的 URL 编码
问题描述
我编写了一个代码来从 API 调用中获取值...它可以正常使用普通 URL,但是当我对 URL 进行编码然后进行调用时意味着它不工作...它给出状态错误 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)
编码网址
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 工作。
解决方案
URL 可能包含的字符非常有限。唯一安全的字符是:
- AZ
- a-z
- 0–9
- _ . ~
如果其他字符被编码,则可以包括它们,例如,(
如果它被编码为可以包括%28
。
某些字符必须根据用途进行编码,特别?
是&
和=
。如果它们用于提供查询参数,则不得对其进行编码;如果它们是查询值的一部分,则必须对其进行编码。
所以编码必须在你构造查询部分之前发生:
- 使用 分别对每个查询值进行编码
URLEncoder.encode(queryValue)
。 - 然后连接查询部分:
query = "expand=" + encodedExpandValue + "&filter=" + encodedFilterValue
. - 然后创建整个 URL。
而且这个/
字符非常有问题,无论它是否出现编码。一些 Web 服务器将始终将其视为路径分隔符。最好在查询部分避免它。
推荐阅读
- python - 在 Maya Python 中更新对象名称的问题
- html - 如何将“-”放入表单html
- c# - 在 Xamarin android 活动之间传递数据
- reactjs - React 有时不使用更新的源文件
- amazon-eks - Populating AWS Alb Ingress Annotations from ConfigMap
- python - 如何防止在 django 中提交带有空 CKEditor 的表单
- html - 如何从轮播引导程序中删除灰色空间
- reactjs - React 样式的组件传递图像 url 属性以在每页显示不同的图像?
- javascript - ECharts可以创建风玫瑰图吗?
- javascript - 如何根据角度 6 中的条件验证输入字段