本文介绍了如何在java中构建url?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用StringBuilder构建一个String

I am building a String with StringBuilder

StringBuilder builder = new StringBuilder();
builder.append("my parameters");
builder.append("other parameters");

然后我建立一个网址

Url url = new Url(builder.toString());

然后我尝试连接

HttpURLConnection connection = (HttpURLConnection) url.openConnection();

但是网址似乎与我得到的结果不对。这就像某些参数被错误传递。这就是为什么我认为问题出在StringBuilder的一部分。

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.

问题在于我试图传递的双参数。

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"

是否需要UrlEncoding?我将尝试下面建议的内容。

Is UrlEncoding necessary? I will try what is suggested below.

推荐答案

尝试apache的 URIBuilder : [文档]

Try apache's URIBuilder : [Documentation]

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>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.1</version>
</dependency>

这篇关于如何在java中构建url?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 11:42