java.net.MalformedURLException:基于使用URLEncoder修改的字符串的URL上没有协议

2022-09-01 04:39:48

所以我试图在URL中使用此字符串:-

http://site-test.com/Meetings/IC/DownloadDocument?meetingId=c21c905c-8359-4bd6-b864-844709e05754&itemId=a4b724d1-282e-4b36-9d16-d619a807ba67&file=\\s604132shvw140\Test-Documents\c21c905c-8359-4bd6-b864-844709e05754_attachments\7e89c3cb-ce53-4a04-a9ee-1a584e157987\myDoc.pdf

在此代码中: -

String fileToDownloadLocation = //The above string
URL fileToDownload = new URL(fileToDownloadLocation);
HttpGet httpget = new HttpGet(fileToDownload.toURI());

但是在这一点上,我得到错误:-

java.net.URISyntaxException: Illegal character in query at index 169:Blahblahblah

我意识到通过一些谷歌搜索,这是由于URL中的字符(猜测&),所以我然后添加了一些代码,所以它现在看起来像这样: -

String fileToDownloadLocation = //The above string
fileToDownloadLocation = URLEncoder.encode(fileToDownloadLocation, "UTF-8");
URL fileToDownload = new URL(fileToDownloadLocation);
HttpGet httpget = new HttpGet(fileToDownload.toURI());

但是,当我尝试运行此命令时,当我尝试创建URL时,我收到错误,然后错误如下:-

java.net.MalformedURLException: no protocol: http%3A%2F%2Fsite-test.testsite.com%2FMeetings%2FIC%2FDownloadDocument%3FmeetingId%3Dc21c905c-8359-4bd6-b864-844709e05754%26itemId%3Da4b724d1-282e-4b36-9d16-d619a807ba67%26file%3D%5C%5Cs604132shvw140%5CTest-Documents%5Cc21c905c-8359-4bd6-b864-844709e05754_attachments%5C7e89c3cb-ce53-4a04-a9ee-1a584e157987%myDoc.pdf

看起来我无法进行编码,直到我创建了URL之后,否则它会替换斜杠和不应该替换的东西,但是我看不到如何使用字符串创建URL,然后格式化它以使其适合使用。我对所有这些不是特别熟悉,并希望有人能够向我指出我缺少什么,以便将字符串A放入适当格式的URL中,然后使用正确的字符替换?

任何建议都非常感谢!


答案 1

在将参数值连接到 URL 之前,您需要对参数值进行编码。
反斜杠是特殊字符,必须转义为\%5C

转义示例:

String paramValue = "param\\with\\backslash";
String yourURLStr = "http://host.com?param=" + java.net.URLEncoder.encode(paramValue, "UTF-8");
java.net.URL url = new java.net.URL(yourURLStr);

结果是格式正确的 url 字符串。http://host.com?param=param%5Cwith%5Cbackslash


答案 2

我有同样的问题,我用属性文件读取网址:

String configFile = System.getenv("system.Environment");
        if (configFile == null || "".equalsIgnoreCase(configFile.trim())) {
            configFile = "dev.properties";
        }
        // Load properties 
        Properties properties = new Properties();
        properties.load(getClass().getResourceAsStream("/" + configFile));
       //read url from file
        apiUrl = properties.getProperty("url").trim();
            URL url = new URL(apiUrl);
            //throw exception here
    URLConnection conn = url.openConnection();

开发属性

url = "https://myDevServer.com/dev/api/gate"

它应该是

开发属性

url = https://myDevServer.com/dev/api/gate

没有“”,我的问题就解决了。

根据预言机文档

  • 抛出以指示发生了格式错误的 URL。要么在规范字符串中找不到合法协议,要么无法解析该字符串。

所以这意味着它没有在字符串内解析。


推荐