从 Java 中的相对 URL 构建绝对 URL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1389184/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:32:30  来源:igfitidea点击:

Building an absolute URL from a relative URL in Java

javaurlrelative-url

提问by Marty Pitt

I'm having trouble building an absolute URL from a relative URL without resorting to String hackery...

我在不诉诸字符串黑客的情况下从相对 URL 构建绝对 URL 时遇到问题......

Given

给定的

http://localhost:8080/myWebApp/someServlet

Inside the method:

方法内部:

   public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}

What's the most "correct" way of building :

什么是最“正确”的构建方式:

http://localhost:8080/myWebApp/someImage.jpg

(Note, must be absolute, not relative)

(注意,必须是绝对的,不是相对的)

Currently, I'm doing it through building the string, but there MUST be a better way.

目前,我正在通过构建字符串来做到这一点,但必须有更好的方法。

I've looked at various combinations of new URI / URL, and I end up with

我查看了新 URI / URL 的各种组合,最终得到了

http://localhost:8080/someImage.jpg

Help greatly appreciated

非常感谢帮助

采纳答案by Hamza Yerlikaya

Using java.net.URL

使用 java.net.URL

 URL baseUrl = new URL("http://www.google.com/someFolder/");
 URL url = new URL(baseUrl, "../test.html");

回答by ZZ Coder

Looks like you already figured out the hard part, which is what host your are running on. The rest is easy,

看起来您已经弄清楚了困难的部分,即您正在运行的主机。剩下的就简单了

String url = host + request.getContextPath() + "/someImage.jpg";

Should give you what you need.

应该给你你需要的。

回答by JRL

How about:

怎么样:

String s = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/someImage.jpg";

回答by Forer

this code work will on linux, it can just combine the path, if you want more, constructor of URI could be helpful.

此代码将在linux上工作,它可以只组合路径,如果您想要更多,URI 的构造函数可能会有所帮助。

URL baseUrl = new URL("http://example.com/first");
URL targetUrl = new URL(baseUrl, Paths.get(baseUrl.getPath(), "second", "/third", "//fourth//", "fifth").toString());

if you path contain something need to escape, use URLEncoder.encodeto escape it at first.

如果您的路径包含需要URLEncoder.encode转义的内容,请首先使用转义它。

URL baseUrl = new URL("http://example.com/first");
URL targetUrl = new URL(baseUrl, Paths.get(baseUrl.getPath(), URLEncoder.encode(relativePath, StandardCharsets.UTF_8), URLEncoder.encode(filename, StandardCharsets.UTF_8)).toString());

example:

例子:

import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Main {
    public static void main(String[] args) {
        try {
            URL baseUrl = new URL("http://example.com/first");
            Path relativePath = Paths.get(baseUrl.getPath(), "second", "/third", "//fourth//", "fifth");
            URL targetUrl = new URL(baseUrl, relativePath.toString());
            System.out.println(targetUrl.toString());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
}

output

输出

http://example.com/first/second/third/fourth/fifth

baseUrl.getPath()are very important, don't forget it.

baseUrl.getPath()很重要,不要忘记。

a wrong example:

一个错误的例子:

import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Main {
    public static void main(String[] args) {
        try {
            URL baseUrl = new URL("http://example.com/first");
            Path relativePath = Paths.get("second", "/third", "//fourth//", "fifth");
            URL targetUrl = new URL(baseUrl, relativePath.toString());
            System.out.println(targetUrl.toString());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
}

output

输出

http://example.com/second/third/fourth/fifth

we have lost our /firstin baseurl.

我们/first在 baseurl 中丢失了。