在java中构建URL [英] Build URL in java
问题描述
尝试构建 http://IP:4567/foldername/1234?abc=xyz
.我对此知之甚少,但我从谷歌搜索中编写了以下代码:
Trying to build http://IP:4567/foldername/1234?abc=xyz
. I don't know much about it but I wrote below code from searching from google:
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?
.我被困在查询部分.请帮助我前进.
I am able to build URL http://IP:port/foldername/1234?
. I am stuck at query part. Please help me to move forward.
推荐答案
在一般的非 Java 术语中,URL 是一种特殊类型的 URI.您可以使用 URI 类(这是比古老的 URL 类(自 Java 1.0 以来一直存在)更现代,以更可靠地创建 URI,并且您可以使用 toURL URI的方法:
In general non-Java terms, a URL is a specialized type of URI. You can use the URI class (which is more modern than the venerable URL class, which has been around since Java 1.0) to create a URI more reliably, and you can convert it to a URL with the toURL method of URI:
String protocol = "http";
String host = "example.com";
int port = 4567;
String path = "/foldername/1234";
String auth = null;
String fragment = null;
URI uri = new URI(protocol, auth, host, port, path, query, fragment);
URL url = uri.toURL();
注意path
需要以斜线开头.
这篇关于在java中构建URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!