Forums Register Login

How to retrieve file contents using sockets

+Pie Number of slices to send: Send
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?
+Pie Number of slices to send: Send
 

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

+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
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.
Time is mother nature's way of keeping everything from happening at once. And this is a tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 1018 times.
Similar Threads
trouble retrieving html of all web sites
InputStreams reading text and bytes from socket
Error calling Servlet from java file, while Servlet downloading file from website
Uploading Image from Java Desktop App to Server
Getting the URL by crawling whose content-type is not text/html
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 03:37:31.