What is the preferred way to read / write content from a url in Java

What is the preferred way to open a connection to a website and then read the information on this page? There seem to be many specific questions about the different parts, but there are no clear and simple examples.

+4
source share
4 answers

Retrieving Text from a URL | Depot example :

try { // Create a URL for the desired page URL url = new URL("http://hostname:80/index.html"); // Read all the text returned by the server BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { // str is one line of text; readLine() strips the newline character(s) } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } 

When it comes to โ€œwritingโ€ to the URL, I assume you need something like Submitting a POST request using the URL | Depot example .

+5
source

Sun Microsystems actually has a URLConnection reading and writing tutorial on this topic, which would be a good starting place.

+1
source

You can simply use this:

 InputStream stream = new URL( "http://google.com" ).openStream(); 
+1
source

Sun Microsystems SB related article is a good place to start. However, I would definitely not call this the preferred way. First, he throws an exception unnecessarily, then he does not close the threads at the end. In addition, it uses the url.openStream method, which I disagree with, since it can still receive output, even if an HTTP Error is returned .

Instead of url.openStream we write:

 HttpURLConnection conn=(HttpURLConnection) url.openConnection() //Any response code starting with 2 is acceptable if(!String.valueOf(conn.getResponseCode()).startsWith('2')) //Provide a nice useful exception throw new IOException("Incorrect response code "+conn.getResponseCode()+" Message: " +getResponseMessage()); InputStream rawIn=conn.getInputStream() OutputStream rawOut=conn.getOutputStream() //You may want to add buffering to reduce the number of packets sent BufferedInputStream bufIn=new BufferedInputStream(rawIn); BufferedOutputStream bufOut=new BufferedInputStream(rawOut); 

DO NOT USE THIS CODE WITHOUT PROCESSING EXCEPTIONS OR CLOSING FLOWS! . This is actually quite difficult to do correctly. If you want to see how to do it right, look at my answer to the much more specific question of selecting images in Android , since I do not want to rewrite all of this here.

Now, when you download input from the server, if you are not writing a command line tool, you need to run it in a separate stream and display the download dialog. Sgarman's answer demonstrates this using the main Java threads, and my answer to this question is using the AsyncTask class from Android to make it tidier . The class file has no dependencies on Android, and the license is Apache, so you can use it in projects other than Android.

-3
source

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


All Articles