Snowman08 Snowman08 - 1 month ago 16
Java Question

Keep getting java.net.MalformedURLException: no protocol when setting url with variable

I keep getting no protocol on a url when I try to change it from a string to a url. Any help would be greatly appreciated!

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 ??


I added weather_pic to show what its doing

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;
}


See if its actually has a value and it does

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

Answer

You are using cond.get("icon_url").toString() which adds " at start and end of result:

"http://icons.wxug.com/i/c/k/partlycloudy.gif"
^                                            ^

so URL finds that " instead of protocol, and complains about it.

Use cond.get("icon_url").getAsString() instead to get rid that extra ".

Comments