Read from java url

I am trying to read the url in java and it works as long as the url loads in the browser.

But if it just loops in the browser and doesn't load this page when I try to open it in my browser, my java application just freezes, it will probably wait forever if there is enough time. How to set a timeout on something or something if it takes more than 20 seconds to stop the application?

I am using URL

Here is the important part of the code:

URL url = null; String inputLine; try { url = new URL(surl); } catch (MalformedURLException e) { e.printStackTrace(); } BufferedReader in; try { in = new BufferedReader(new InputStreamReader(url.openStream())); while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); } in.close(); } catch (IOException e) { e.printStackTrace(); } 
+6
source share
4 answers

I do not know how you use the URL class. It would be better if I posted a fragment. But here is a way that works for me. See if this helps in your case:

  URL url = new URL(urlPath); URLConnection con = url.openConnection(); con.setConnectTimeout(connectTimeout); con.setReadTimeout(readTimeout); InputStream in = con.getInputStream(); 
+10
source

The URL method # openStream is actually a shortcut to openConnection().getInputStream() . Here is the code from the URL class:

 public final InputStream openStream() throws java.io.IOException { return openConnection().getInputStream(); } 
  • You can configure the settings in the client code as follows:

     URLConnection conn = url.openConnection(); // setting timeouts conn.setConnectTimeout(connectTimeoutinMilliseconds); conn.setReadTimeout(readTimeoutinMilliseconds); InputStream in = conn.getInputStream(); 

Ref: URLConnection # setReadTimeout , URLConnection # setConnectTimeout

  • In addition, you should set the sun.net.client.defaultConnectTimeout and sun.net.client.defaultReadTimeout system property to a reasonable value.
+2
source

If you use URLConnection (or HttpURLConnection ) to "read from a URL", you have a setReadTimeout() method that allows you to control this.

Edited after posting the code:

 URL url = null; String inputLine; try { url = new URL(surl); } catch (MalformedURLException e) { e.printStackTrace(); } BufferedReader in; try { URLConnection con = url.openConnection(); con.setReadTimeout( 1000 ); //1 second in = new BufferedReader(new InputStreamReader(con.getInputStream())); while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); } in.close(); } catch (IOException e) { e.printStackTrace(); } 
+1
source

You must add internet permission to AndroidMenifest.xml

 <uses-permission android:name="android.permission.INTERNET" /> 

and add it to the main function:

 if (android.os.Build.VERSION.SDK_INT > 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); } 
0
source

Source: https://habr.com/ru/post/890003/


All Articles