HttpURLConnection从服务器获取内容长度

时间:2017-01-12 11:25:37

标签: java android httpurlconnection

我使用以下连接恢复下载:

connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setReadTimeout(7000);
connection.setRequestProperty("Range", "bytes=" + localFileSize + "-");

long fileLengthOnServer = connection.getContentLength();
connection.connect();

fileLengthOnServer的值为-1。任何人都可以解释fileLengthOnServer成为-1的条件。我想,但不确定localFileSize是否与服务器上的<item name="android:windowFullscreen">true</item> 相同。请帮忙!

1 个答案:

答案 0 :(得分:2)

您需要在long fileLengthOnServer = connection.getContentLength();之后调用此connection.connect()。您无法在不连接服务器的情况下获取响应标头