Read from URL java

后端 未结 4 1268
抹茶落季
抹茶落季 2021-01-03 00:57

I\'m trying to read URL in java, and it works as long as the URL is loading in browser.

But if it is just cylcing in the browser and not loading that page when I\'m

相关标签:
4条回答
  • 2021-01-03 01:05

    I don't know how u are using the URL class. It would have been better if post a snippet. But here is a way that works for me. See if it helps in your case:

        URL url = new URL(urlPath);
        URLConnection con = url.openConnection();
        con.setConnectTimeout(connectTimeout);
        con.setReadTimeout(readTimeout);
        InputStream in = con.getInputStream();
    
    0 讨论(0)
  • 2021-01-03 01:05

    If you are using a URLConnection (or HttpURLConnection) to "read from a url" you have a setReadTimeout() method which allows you to control that.

    Edited after you posted 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();
    }
    
    0 讨论(0)
  • 2021-01-03 01:15

    You should add internet permission in AndroidMenifest.xml

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

    and add it in the main function:

    if (android.os.Build.VERSION.SDK_INT > 9)
            {
                StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                StrictMode.setThreadPolicy(policy);
            }
    
    0 讨论(0)
  • 2021-01-03 01:18

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

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

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

    Reference: URLConnection#setReadTimeout, URLConnection#setConnectTimeout

    • Alternatively, you should set the sun.net.client.defaultConnectTimeout and sun.net.client.defaultReadTimeout system property to a reasonable value.
    0 讨论(0)
提交回复
热议问题