【问题标题】:java.net.MalformedURLException: no protocol on URL based on a string modified with URLEncoderjava.net.MalformedURLException:基于使用 URLEncoder 修改的字符串的 URL 没有协议
【发布时间】:2014-02-28 11:26:06
【问题描述】:

所以我试图在 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,然后替换正确的字符?

任何建议都非常感谢!

【问题讨论】:

标签: java uri malformedurlexception


【解决方案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);

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

【讨论】:

  • 感谢特殊字符的提醒!我在fileToDownloadLocation = fileToDownloadLocation.replace("\\", "%5C"); 行中添加了,嘿,一切都好起来了,好简单的修复让我度过难关,干杯! :)
  • 这不适用于带有空格的文件...同样,URLEncoder.encode() 不适用于 URI!
  • 空格将被替换为加号“+”字符。这是对 URL 的正确转义。
【解决方案2】:

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

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();

dev.properties

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

应该是

dev.properties

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

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

根据oracledocumentation

  • 抛出表示出现了格式错误的 URL。在规范字符串或字符串中找不到合法协议 无法解析。

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

【讨论】:

  • 同样的问题,但来自export THE_URL="<url>"
【解决方案3】:

您想使用URI templates。仔细查看这个项目的 README:URLEncoder.encode() 不适用于 URI。

让我们获取您的原始网址:

http://site-test.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

并将其转换为带有两个变量的 URI 模板(为清楚起见,在多行上):

http://site-test.test.com/Meetings/IC/DownloadDocument
    ?meetingId={meetingID}&itemId={itemID}&file={file}

现在让我们使用链接中提到的库用这三个变量构建一个变量映射:

final VariableMap = VariableMap.newBuilder()
    .addScalarValue("meetingID", "c21c905c-8359-4bd6-b864-844709e05754")
    .addScalarValue("itemID", "a4b724d1-282e-4b36-9d16-d619a807ba67e")
    .addScalarValue("file", "\\\\s604132shvw140\\Test-Documents"
        + "\\c21c905c-8359-4bd6-b864-844709e05754_attachments"
        + "\\7e89c3cb-ce53-4a04-a9ee-1a584e157987\\myDoc.pdf")
    .build();

final URITemplate template
    = new URITemplate("http://site-test.test.com/Meetings/IC/DownloadDocument"
        + "meetingId={meetingID}&itemId={itemID}&file={file}");

// Generate URL as a String
final String theURL = template.expand(vars);

保证返回一个功能齐全的 URL!

【讨论】:

  • 感谢您的详细回复,我想如果我想实现这一点,我必须从 github 等下载我会调查的东西,干杯!
【解决方案4】:

感谢二浑的回答,我终于意识到我的 JSON 映射器也在返回我的数据周围的引号!我需要使用“asText()”而不是“toString()

这不是一个罕见的问题 - 一个人的大脑不会发现正确的数据有任何问题,用引号括起来!

discoveryJson.path("some_endpoint").toString();
"https://what.the.com/heck"

discoveryJson.path("some_endpoint").asText();
https://what.the.com/heck

【讨论】:

    【解决方案5】:

    这段代码对我有用

    public static void main(String[] args) {
        try {
            java.net.URL url = new java.net.URL("http://path");
            System.out.println("Instantiated new URL: " + url);
        }
        catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
    

    实例化的新 URL:http://path

    【讨论】:

      【解决方案6】:

      非常简单的修复

      字符串编码URL = UriUtils.encodePath(request.getUrl(), "UTF-8");

      无需额外功能即可工作。

      【讨论】:

        猜你喜欢
        • 2010-12-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-24
        • 2011-01-10
        • 2014-05-24
        • 2016-01-15
        • 1970-01-01
        相关资源
        最近更新 更多