networking - fetching a webpage using java socket class -


good evening of
want fetch webpage using socket class in java , have done as

import java.net.*; import java.io.*;  class htmlpagefetch{         public static void main(string[] args){                 try{                         socket s = new socket("127.0.0.1", 80);                         datainputstream din = new datainputstream(s.getinputstream());                         dataoutputstream dout = new dataoutputstream(s.getoutputstream());                         dout.write("get /index.php http/1.0\n\n".getbytes());                         boolean more_data = true;                         string str;                         while(more_data){                                 str = din.readline(); if(str==null) more_data = false;                                 system.out.println(str);                         }                 }catch(ioexception e){                  }         } } 

but giving null's.

output

 http/1.1 302 found date: wed, 01 dec 2010 13:49:02 gmt server: apache/2.2.11 (unix) dav/2 mod_ssl/2.2.11 openssl/0.9.8k php/5.2.9 mod_apreq2-20051231/2.6.0 mod_perl/2.0.4 perl/v5.10.0 x-powered-by: php/5.2.9 location: http://localhost/xampp/ content-length: 0 content-type: text/html  null 

i'm not sure if causing problem, http expects carriage return , line feed newline:

dout.write("get /index.php http/1.0\r\n\r\n".getbytes()); 

also, wouldn't hurt flush , close dataoutputstream:

dout.flush(); dout.close(); 

if plan on doing more code connecting simple test cases, i'd recommending using httpurlconnection instead of implenting http in socket yourself. otherwise, result contain more web page. contain http response including status codes , headers. code need parse that.

update:

looking @ response added, 302 response along location: header indicate page looking moved http://localhost/xampp/ (see http 302) , there no longer content @ original url. can set handled automatically httpurlconnection or library apache httpclient. need parse status code, parse headers, open new socket response location , page. depending upon exact requirements of assignment, want familiarize http 1.0 specification, , http 1.1 specification well.


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -