我有一个任务是在Android (Java平台)中使用HTTP协议下载和上传文件。
我正在使用以下代码来上传文件:
HttpURLConnection httpURLConnection = (HttpURLConnection) serverUrl.openConnection();
....
httpURLConnection.connect();
OutputStream os = httpURLConnection.getOutputStream();并使用以下代码下载文件:
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
...
urlConnection.connect();
DataInputStream stream = new DataInputStream(urlConnection.getInputStream());根据我的观察,这两种情况的connect()都需要时间,因为此时它正在与网络通信。对于文件上传,getOutputStream()的执行速度非常快,所以这是否意味着它不会与网络通信?
而getInputStream() (在文件下载中)需要一些时间(大约200到2500毫秒)来执行。这是否意味着它此时正在与网络通信?如果是,那为什么呢?
专家们,请提供您对此的意见,如果我错了,请纠正我。
发布于 2014-04-16 03:24:01
HTTP是一种请求/响应协议。您需要TCP连接。connect()方法就是这样创建的。然后你需要发送一个请求。为此调用getOutputStream(),然后编写它。
此时还没有向网络写入任何内容(在正常传输模式下),因为必须设置content-length报头,而Java不知道您何时完成了写入。因此,当您调用getInputStream() (或getResponseCode())时,Java设置content-length头部,编写请求,等待服务器开始生成响应,读取所有响应头,然后向您提供位于响应体开头的输入流。所有这些步骤都需要时间。
发布于 2018-02-26 21:05:39
您必须通过指定流模式来限制缓冲,方法是通过setFixedLengthStreamingMode方法提供上传信息的最终长度,或者如果通过setChunkedStreamingMode方法未知最终长度,则将模式设置为流:
// For best performance, you should call either setFixedLengthStreamingMode(int) when the body length is known in advance,
// or setChunkedStreamingMode(int) when it is not. Otherwise HttpURLConnection will be forced to buffer the complete request body in memory
// before it is transmitted, wasting (and possibly exhausting) heap and increasing latency.
//
// see: https://developer.android.com/reference/java/net/HttpURLConnection.html
_connection.setChunkedStreamingMode(1024);如果不这样做,真正的传输将在您调用getInputStream()时发生。
请参阅https://developer.android.com/reference/java/net/HttpURLConnection.html
https://stackoverflow.com/questions/23086731
复制相似问题