在 Java 中构建 URL

新手上路,请多包涵

尝试构建 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? 。我被困在查询部分。请帮助我前进。

原文由 rrr ppp 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 779
2 个回答

在一般的非 Java 术语中,URL 是一种特殊类型的 URI。您可以使用 URI 类(它比自 Java 1.0 以来就存在的古老的 URL 类更现代)来更可靠地创建 URI,并且您可以使用 URI 的 toURL 方法将其转换为 URL:

 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 需要以斜杠开头。

原文由 VGR 发布,翻译遵循 CC BY-SA 3.0 许可协议

你可以通过原始规格

new URL("http://IP:4567/foldername/1234?abc=xyz");

或者你可以采取类似 org.apache.http.client.utils.URIBuilder 的东西,并使用适当的 url 编码以安全的方式构建它

URIBuilder builder = new URIBuilder();
builder.setScheme("http");
builder.setHost("IP");
builder.setPath("/foldername/1234");
builder.addParameter("abc", "xyz");
URL url = builder.build().toURL();

原文由 vsminkov 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏