【发布时间】:2017-01-22 18:02:00
【问题描述】:
尝试构建http://IP:4567/foldername/1234?abc=xyz。我对此了解不多,但我通过谷歌搜索编写了以下代码:
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
public class MyUrlConstruct {
public static void main(String a[]){
try {
String protocol = "http";
String host = "IP";
int port = 4567;
String path = "foldername/1234";
URL url = new URL (protocol, host, port, path);
System.out.println(url.toString()+"?");
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
}
}
我能够建立 URL http://IP:port/foldername/1234?。我被困在查询部分。请帮助我前进。
【问题讨论】:
-
@px06 url 需要转义和验证,concat 不会削减它,因为如果
abc=xyz包含其他一些=, ? or &它将被破坏。为此使用专用的库,但对于极其简单的情况 concat 可能会起作用。 -
从 Java 7 开始,有一个 (EE) 内置函数
javax.ws.rs.core.UriBuilder可以为您执行此操作。