繁体   English   中英

克服java.net.MalformedURLException:没有协议异常

[英]Overcoming java.net.MalformedURLException: no protocol Exception

我有一个属性文件,其中包含一个属性,指定包含温度数据集的NOAA网站的URL。 该属性包含[DATE_REPLACE]标记,因为当NOAA生成新预测时,URL会每天更改。

在我的属性文件中,我指定:

WEATHER_DATA_URL="http://weather.noaa.gov/pub/SL.us008001/DF.anf/DC.mos/DS.mex/RD.[DATE_REPLACE]/cy.00.txt"

我已经声明了一个带有PropertyHelper类(java.util.Properties的包装器)的方法,使用WEATHER_DATA_URL作为名称生成当前日期的URL字符串,使用“ yyyyMMdd ”作为日期格式,即今天的日期。

public String getPropertyWithDateReplaceToken(String name, String dateFormat, Date dateToFormat)
{
    String value = this.properties.getProperty(name);

    if (StringHelper.isNullOrWhitespace(value) || !value.contains("[DATE_REPLACE]"))
    {
        throw new UnsupportedOperationException("The property value should specify the [DATE_REPLACE] token");
    }

    StringBuilder sb = new StringBuilder(value);
    int index = sb.indexOf("[DATE_REPLACE]");
    while (index != -1)
    {
        String replacement = StringHelper.getTodayAsDateString(dateFormat, dateToFormat);
        sb.replace(index, index + "[DATE_REPLACE]".length(), replacement);
        index += replacement.length();
        index = sb.indexOf(value, index);
    }

    return sb.toString();
}

然后,我使用以下方法调用另一个帮助器类来从网页中读取文本:

public static List<String> readLinesFromWebPage(String urlText) throws Exception
{
    List<String> lines = new ArrayList<String>();
    if (StringHelper.isNullOrWhitespace(urlText))
    {
        throw new NullPointerException("URL text cannot be null or empty");
    }

    BufferedReader dataReader = null;
    try
    {
        System.out.println("URL = " + urlText);
        String trimmedUrlText = urlText.replaceAll("\\s", "");

        URL url = new URL(trimmedUrlText);
        dataReader = new BufferedReader(new InputStreamReader(url.openStream()));

        String inputLine;
        while((inputLine = dataReader.readLine()) != null)
        {
            lines.add(inputLine);
        }

        return lines; 
    }
    catch(Exception e)
    {
        logger.logThrow(Level.SEVERE, e, "Exception (" + e.getMessage() + ") attempting to " +
                "read data from URL (" + urlText + ")");
        throw e;
    }
}

正如您所看到的,我试图从生成的URL字符串中修剪空格,希望这会导致问题。 URL字符串生成正常但我收到以下异常:

java.net.MalformedURLException: no protocol: "http://weather.noaa.gov/pub/SL.us008001/DF.anf/DC.mos/DS.mex/RD.20121219/cy.00.txt"

如果我手动设置字符串,一切正常......我错过了什么?

您的属性文件在URL的值周围有双引号。 删除这些。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM