How to Read through HTTP in Java

Guess, that's simple too. How would you get http object (web page) from Java? Sockets? No. There is much more easy way. It uses URLConnection object and InputStream. You set URLConnection, you get InputStream from there, and then you just read it like you would read any file. That's simple. The only catch is security, you cannot access files in Java applet and you cannot access pages from another server from applet if security settings in the browser are not seriously lowered. Also you are getting byte array byte[], so you have to convert it to String to see the text (remember, it's Java, in Java text is Unicode!).

To put it simple, just see the code. I already wrote more explanation that the code takes for itself :-).



And here is how to do that (only read part, of course, add GUI as needed):

public void button1_ActionEvents() { try { // this code reads up to 4K, to read more put read/convert into a loop until r==0 byte buf[] = new byte[4048]; URL url = new URL(ivjTextField1.getText()); URLConnection urlConnection = url.openConnection(); urlConnection.connect(); InputStream is = urlConnection.getInputStream(); int r = is.read(buf); ivjTextArea1.setText(getRidOfZeroes(buf)); is.close(); } catch (Exception e) { ivjTextArea1.setText("Uh-oh, exception... The message is:"+e+"\n"); } return; }