• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to retrieve file contents using sockets

 
Avan Chua
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I an new to java.

I am trying to retrieving a file content from a given server and file path.
The file could be a text, html or image file.

I tried reading the content as bytes but the image will not display:

The following is a segment of my code:

byte[] b = new byte[1024];

Socket socket = new Socket(hostname,80);

PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));
out.println("GET /" + file + " HTTP/1.1");
out.println("Host: " + hostname);
out.println();
out.flush();

DataInputStream reader = new DataInputStream(socket.getInputStream());

int i = 10;
File outputfile = new File(outFileName);
FileOutputStream outfile = new FileOutputStream(outputfile);

while ((i = reader.read(b)) != -1) {
outfile.write(b,0, i);
}

I was able to read the contents for text and html but not image file, I do not know why?!. In addition, my output file will contain the http response code which I want to omit but could not
as I am reading everything as bytes, I would not know the particular position the http response code ends to decide which to write and what item not to write.

Can anyone help with my 2 questions?
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13071
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was able to read the contents for text and html but not image file, I do not know why?!


For one reason - readers perform a character conversion on input bytes.

Furthermore, how are you handling the response headers? Wouldn't it be easier to use the standard library - java.net package HttpURLConnection class?

Bill

 
Avan Chua
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How do I use it? the HttpURL Connection, is there any examples on how to use it that you could show me? I am really new to this.
 
Paul Clapham
Sheriff
Posts: 21322
32
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your web search keywords for that question would be: java HttpURLConnection example. I'm sure you should be able to find an example of that class online if you just search a bit.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic