继续获取java.net.MalformedURLException:使用变量设置url时没有协议

时间:2016-10-20 17:54:51

标签: java

当我尝试将其从字符串更改为网址时,我一直没有在网址上获得协议。任何帮助将不胜感激!

icon_image = weather.weather_pic();
//^ The string icon_image is = http://icons.wxug.com/i/c/k/clear.gif

URL url = new URL("http://icons.wxug.com/i/c/k/clear.gif");


// when I try URL url = new URL(icon_image); it gives me malformed unknown protocal.
// but if i set it like this URL url = new URL("http://icons.wxug.com/i/c/k/clear.gif") it works ??

我添加了weather_pic来展示它的作用

public static String weather_pic() throws IOException {

    // Connect to the URL using java's native library
    String sURL = "http://api.wunderground.com/api/84b167e6ec916b78/conditions/q/NV/Reno.json"; //just a string
    URL url = null;
    try {
        url = new URL(sURL);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    HttpURLConnection request = null;
    try {
        request = (HttpURLConnection) url.openConnection();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        request.connect();
    } catch (IOException e) {
        e.printStackTrace();
    }

    // Convert to a JSON object to print data
    JsonParser jp = new JsonParser(); //from gson
    JsonElement root = null; //Convert the input stream to a json element
    try {
        root = jp.parse(new InputStreamReader((InputStream) request.getContent()));
    } catch (IOException e) {
        e.printStackTrace();
    }

    JsonObject rootobj = root.getAsJsonObject(); //May be an array, may be an object.

    JsonObject cond = rootobj.get("current_observation").getAsJsonObject();

    String icon = cond.get("icon_url").toString();

    System.out.println(icon);
    //String zipcode = rootobj.get("query").getAsString(); //just grab the zipcode
    String icon_x  = icon;



    return icon_x;
}

查看它实际上是否有值,它确实

Exception in thread "main" java.net.MalformedURLException: no protocol: "http://icons.wxug.com/i/c/k/partlycloudy.gif"
    at java.net.URL.<init>(URL.java:593)
    at java.net.URL.<init>(URL.java:490)
    at java.net.URL.<init>(URL.java:439)
    at widget.Widget.<init>(Widget.java:42)
    at widget.Widget.main(Widget.java:75)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
"http://icons.wxug.com/i/c/k/partlycloudy.gif"

Process finished with exit code 1

1 个答案:

答案 0 :(得分:7)

您正在使用var chartTypeContent = new google.visualization[chartType](document.getElementById('chart_div')); 围绕字符串结果cond.get("icon_url").toString(),就像您的情况一样:

"

当URL在启动时发现"http://icons.wxug.com/i/c/k/partlycloudy.gif" ^ ^ 而不是协议名称时,它会抱怨它。

解决这个问题并摆脱额外的"使用

"