0

I need a java program to download a series of file from a web server and I need to be able to close and then reopen the tcp/ip connection between each file download.

Not sure how to do this.

Steve Kuo
  • 61,876
  • 75
  • 195
  • 257
BourneAgain
  • 71
  • 1
  • 2
  • 7

3 Answers3

1

Here is a low-level way of retrieving any information from not only socket 80 (http) but generically to retrieve mail, do a 'telnet' etc:

socket = new Socket();
socket.connect(new InetSocketAddress(host, port));
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

now to do a call to retrieve a page, send the get command, set the content-type, and send two '\n'.

There is a higher-level solution: Send HTTP GET request with header

Community
  • 1
  • 1
SunKing2
  • 311
  • 2
  • 10
  • Thanks. That's what I'm looking for. Appreciate the fast response. – BourneAgain Mar 29 '12 at 14:59
  • Just a follow up question. Once I close the socket and I try to use it again (socket.connect(new InetSocketAddress(host,80));) I receive a java.net.SocketException: Socket is closed error. I can't seem to reopen it. So I am just declaring Socket socket = new Socket();,Socket socket2 = new Socket();, etc... for how many ever files I am getting in the code. Is this the correct way or can I reopen the socket I closed somehow? – BourneAgain Mar 29 '12 at 15:05
  • It's been awhile since I've coded like this, but from what I remember, the intention of this code was to make a stateless call (ie, get the data, then close the streams and sockets) and end the program (which I left out). To make several http calls, you could create 1. a socket object, and 2. an InetSocketAddress object. Then for each call, just modify the fields of the InetSocketAddress (by calling some set methods on it), create a new reader and writer, get the page, then perform the close statements. – SunKing2 Mar 29 '12 at 22:59
  • That's what I was thinking also is to just put the socket creation in it own method and call that method for each file GET. Thanks. – BourneAgain Mar 30 '12 at 13:25
0

You can create a Socket for the IP and port you want to send it to, then read the file into a byte array using a FileInputStream and send that byte array through a DataOutPutStream, then when done just flush the dataOutPutStream and close the Socket and call the function again sending the next file.

Kevin
  • 532
  • 2
  • 7
0

use the logic: Please post something that you have tried.

 do{
      connection.open;
      while(!eof){
      fetchfiles();
      }
     connection.close;
     }while(no of files yet to download);
special
  • 621
  • 3
  • 11
  • 20