2

According to Android reference you can declare an URL using a string.

That means that the next code is supposed to be correct(i.e):

 URL url = new URL("http://www.android.com/");

When I try to use it I get:

"java.net.MalformedURLException"

It happens to me on AndroidStudio 1.2.1.1

The full code I'm trying to use comes from the references of HttpURLConnect of Android:

 URL url = new URL("http://www.android.com/");
   HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
   try {
     InputStream in = new BufferedInputStream(urlConnection.getInputStream());
     readStream(in);
    finally {
     urlConnection.disconnect();
   }
 }
Jonny C
  • 1,943
  • 3
  • 20
  • 36
SamuelPS
  • 555
  • 6
  • 20

2 Answers2

2

Look at this:

Java Malformed URL Exception

The answer says: It is not raising the error, it's complaining that you haven't handled the possibility that it might, even though it won't, because the URL in this case is not malformed. Java seems to think this is a good idea. (It's not.)

To shut it up, add throws MalformedURLException or throws IOException to the method declaration. E.g.:

public void myMethod() throws IOException {
    URL url = new URL("https://wikipedia.org/");
}
Community
  • 1
  • 1
UtsavShah
  • 857
  • 1
  • 9
  • 20
2

This works perfectly fine here

try {

    URL url = new URL("http://www.android.com/");
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

    BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }

    urlConnection.disconnect();

} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
theapache64
  • 10,926
  • 9
  • 65
  • 108