如何在java中构建url?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26641809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to build url in java?
提问by Manolis Karamanis
I am building a String with StringBuilder
我正在用 StringBuilder 构建一个字符串
StringBuilder builder = new StringBuilder();
builder.append("my parameters");
builder.append("other parameters");
Then i build a Url
然后我建立一个网址
Url url = new Url(builder.toString());
And then i try the connection
然后我尝试连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
But the url seems not to be right from the results i get. It's like some parameter is being false passed. That's why i think the problem is in the part of the StringBuilder.
但是从我得到的结果来看,这个 url 似乎不正确。就像某些参数被错误传递一样。这就是为什么我认为问题出在 StringBuilder 的一部分。
The problem is in a double parameter i try to pass.
问题出在我尝试传递的双参数中。
double longitude = 23.433114;
String lng = String.ValueOf(longitude);
And then i put it in the url. But if i give it as a string the result is correct.
然后我把它放在网址中。但是如果我把它作为一个字符串给出,结果是正确的。
String lng = "23.433114"
Is UrlEncoding necessary? I will try what is suggested below.
需要 UrlEncoding 吗?我会尝试下面的建议。
采纳答案by jhkuperus
Try apache's URIBuilder
: [Documentation]
尝试 apache 的URIBuilder
:[文档]
import org.apache.http.client.utils.URIBuilder;
// ...
URIBuilder b = new URIBuilder("http://example.com");
b.addParameter("t", "search");
b.addParameter("q", "apples");
Url url = b.build().toUrl();
Maven dependency:
Maven 依赖:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.1</version>
</dependency>
回答by Luiggi Mendoza
Since you want to create the URL and consume it through a GET request, it would be better to use a library that helps you in this process. You can use HttpComponentsor another library like Unirestthat is built on top of HttpComponents which ease all this work.
由于您想创建 URL 并通过 GET 请求使用它,因此最好使用可以帮助您完成此过程的库。您可以使用HttpComponents或其他库,例如构建在 HttpComponents 之上的Unirest,这可以简化所有这些工作。
Here's an example using Unirest:
下面是一个使用 Unirest 的例子:
HttpResponse<String> stringResponse = Unirest.get("https://www.youtube.com/results")
.field("search_query", "e?e")
.asString();
System.out.println(stringResponse.getBody());
This will retrieve the HTML response corresponding to all the results from a search on youtube using "e?e"
. The ?
character will be encoded for you.
这将检索与 youtube 上使用"e?e"
. 该?
字符将被编码为您服务。
DISCLAIMER: I'm not attached to Unirest in any mean. I'm not a developer or a sponsor of this project. I'm only a happy user of this framework.
免责声明:我与 Unirest 没有任何关系。我不是这个项目的开发人员或赞助商。我只是这个框架的快乐用户。