开发者

How to download a file from a server using Java Socket?

开发者 https://www.devze.com 2023-01-31 07:30 出处:网络
I have an assignment about uploading and downloading a file to a server. I managed to do the uploading part using Java Sockets however I am having a hard time doing the downloading part. I should use

I have an assignment about uploading and downloading a file to a server. I managed to do the uploading part using Java Sockets however I am having a hard time doing the downloading part. I should use Range: for downloading parellel. In my request, I should have the Range: header. But I don't understand how I will receive the file with that HTTP GET request. All the examples I have seen was about uplo开发者_运维知识库ading a file. I already did it. I can upload .exe, image, .pdf, anything and when I download them back (by my browser), there are no errors. Can you help me with the downloading part? Can you give me an example beacuse I really didn't get it.


You need to read the HTTP response from the same socket on which you put the request. As a starting point, just print it out. When you are familiar with it, start parsing it. The file will be in there.


This doesn't directly answer your question, but it is (IMO) worth saying anyway ...

If your homework assignment doesn't specifically tell you to use a socket directly, there are simpler, and better ways of doing HTTP file upload and download in Java:

  • Using java.net.URL.openConnection() on an "http:" url will give you an HttpURLConnection that you can use to make GET, PUT, POST and so on requests to the remote server. This takes care of the basic HTTP protocol stuff for you.

  • The Apache HttpClient libraries do the same thing, but in a more sophisticated way, with more options and more hooks for things like handling content (including forms and MIME multiparts), connection and credential management, proxying and route finding and so on.

If the aim of your homework exercise is to teach you practical ways to talk to remote servers, then using these classes is far more practical than trying to implement a subset of the HTTP protocol from the socket level up.

(Of course, the aim could be to give you a deeper understanding of the HTTP protocol at the "wire" level ... which would make your current approach the right one.)


Thank you I did it. I used a byte array and read the input stream and wrote it to a file using fileinputstream and fileoutputstream

0

精彩评论

暂无评论...
验证码 换一张
取 消