tags:

views:

108

answers:

4

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

+1  A: 

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

SB
I originally downvoted this question because I thought that you had simply linked to the API for URLConnection. This would be pointless and lazy since jW would have undoubtedly seen this in the other questions he looked at and doesn't contribute much towards deciding deciding on a preferred method. I only just realised that you actually linked to a Sun Tutorial on almost exactly the same question which is much more useful. So I'll actually upvote it if you edit your answer to make it clearer that you are providing a link that is useful.
Casebash
That's a pretty bad excuse for downvoting. It shows you were too lazy to click the link. Nicely done.
SB
@SB: Lolz, as it is CW I can edit it myself and then upvote it. I think you are taking a single downvote far too seriously, especially since I left a comment so you could challenge my reasons if you disagreed with my downvote. Its only 2 rep!
Casebash
BTW, re: this resource, often the best place to look for coding standards is those resources provided by the company that made the technology. However, in this case, I wouldn't call the method used the preferred way, mainly as they throw Exception rather than writing a try, finally clause.
Casebash
CW doesn't even count towards rep. But on top of that, I normally don't care about a downvote if the reason is good enough. However, I found your reason that you didn't even bother to click the link a rather poor one. That's all. It wasn't worth challenging if you weren't going to bother clicking a link. Usually, the OP wants an example they can cut, paste, and modify. Regardless, thanks for the edit - will try to be clearer next time.
SB
+1  A: 

You can simply use this:

InputStream stream = new URL( "http://google.com" ).openStream();
tangens
-1: Doesn't do the question justice
Casebash
BTW, I recommend against using [url.openStream](http://stackoverflow.com/questions/2986767/is-url-openstream-harmful)
Casebash
+2  A: 

Getting Text from a URL | Example Depot:

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 a URL I suppose you would want something like Sending a POST Request Using a URL | Example Depot.

aioobe
1. I recommend against using [URL.openStream](http://stackoverflow.com/questions/2986767/is-url-openstream-harmful) 2. this doesn't close the stream readers
Casebash
1. why? 2. good point.
aioobe
@aioibe: See the link in the comment. PS. please add a comment in the catch block to emphasise that the exceptions *should be handled* and not ignored.
Casebash
A: 

The Sun Microsystems article linked to by SB would be a good place to start. However, I definitely wouldn't call it the preferred way. First it unnecessarily throws Exception, then it doesn't close the streams in a finally. Additionally, it uses the url.openStream method which I disagree with as it may still receive output even if a 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 HANDLING EXCEPTIONS OR CLOSING THE STREAMS!. This is actually quite hard to do correctly. If you want to see how to do this properly, please look at my answer to the much more specific question of fetching images in Android as I don't want to rewrite it all here.

Now, when retrieving input from the server, unless you are writing a command line tool, you'll want to have run this in a separate thread and display a loading dialogue. Sgarman's answer demonstrates this using basic Java threads, while my an answer to that question using the AsyncTask class from Android to make it neater. The class file doesn't have any Android dependencies and the license is Apache, so you can use it in non-Android projects.

Casebash
I'm curious why you think my answer doesn't do the question justice. He wanted a simple and clear example, which I provided. Your use of Android is irrelevant here since he didn't indicate using it. Why should he pull in an additional class - he could just open a connection and throw it in a thread for async, or use NIO.
SB
@SB: The Android class doesn't have dependencies and is nice enough that I believe that it is worthwhile pulling it in. Alternatively, I also link to an answer by Sgarman which demonstrates doing this with normal threads
Casebash