Why does HTTPURLConnection.getInputStream() takes time

前端 未结 2 1170
北荒
北荒 2020-12-11 22:53

I have a task to download & upload a file using HTTP protocol in Android (Java platform).

I am using following code for uploading a file:

HttpURL         


        
2条回答
  •  南方客
    南方客 (楼主)
    2020-12-11 23:29

    HTTP is a request/response protocol. You need a TCP connection. The connect() method creates that. Then you need to send a request. You call getOutputStream() for that, and you write it.

    At this point nothing has been written to the network (in normal transfer mode), because the content-length header has to be set, and Java doesn't know when you've finished writing. So when you call getInputStream() (or getResponseCode()), Java sets the content-length header, writes the request, waits for the server to start generating a response, reads all the response headers, and then gives you an input stream positioned at the beginning of the body of the response. All those steps take time.

提交回复
热议问题