【问题标题】:getContentLength() returning -1 on some devices and not othersgetContentLength() 在某些设备上返回 -1 而在其他设备上不返回
【发布时间】:2010-09-01 11:28:22
【问题描述】:
我正在尝试在下载文件之前获取文件的大小。我使用conn.getContentLength(); 来执行此操作,它在我的家用电脑 Android 2.1 模拟器上运行良好。
但是,一旦我从手机(WiFi 或 3G)运行我的应用程序,它就无法工作,当我从我的工作笔记本电脑 Android 2.1 模拟器运行它时,它也无法工作。
有人知道解决方法吗?有没有其他方法可以在不使用HttpURLConnection 的情况下获取文件的大小。
【问题讨论】:
标签:
java
android
httpurlconnection
【解决方案1】:
此信息并非始终可用。通常你会知道你正在下载的文件的长度。根据网络服务器、协议、连接和下载方法,这些信息可能并不总是可用。
您绝对应该修改您的应用程序,以便它能够处理这种情况。我想你会发现不同的设备使用不同的连接方式会得到不同的结果。
【解决方案2】:
使用HttpVersion.HTTP_1_0 下载文件。这可以防止使用“分块传输编码”
见:http://en.wikipedia.org/wiki/Chunked_transfer_encoding
例如,重载构造函数,以便您可以指定哪个 HTTP 版本:
public class HTTPrequest
{
//member variables
private SchemeRegistry mSchemeRegistry;
private HttpParams mHttpParams;
private SingleClientConnManager mSCCmgr;
private HttpClient mHttpClient;
private HTTPrequestListener mHTTPrequestListener = null;
//constants
private final int TIMEOUT_CONNECTION = 20000;//20sec
private final int TIMEOUT_SOCKET = 30000;//30sec
//interface for callbacks
public interface HTTPrequestListener
{
public void downloadProgress(int iPercent);
}
/**
* Creates an HttpClient that uses plain text only.
* note: Default constructor uses HTTP 1.1
*/
public HTTPrequest()
{
this(HttpVersion.HTTP_1_1);
}
/**
* Creates an HttpClient that uses plain text only.
* @param httpVersion HTTP Version (0.9, 1.0, 1.1)
*/
public HTTPrequest(HttpVersion httpVersion)
{
//define permitted schemes
mSchemeRegistry = new SchemeRegistry();
mSchemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
//define http parameters
mHttpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(mHttpParams, TIMEOUT_CONNECTION);
HttpConnectionParams.setSoTimeout(mHttpParams, TIMEOUT_SOCKET);
HttpProtocolParams.setVersion(mHttpParams, httpVersion);
HttpProtocolParams.setContentCharset(mHttpParams, HTTP.UTF_8);
//tie together the schemes and parameters
mSCCmgr = new SingleClientConnManager(mHttpParams, mSchemeRegistry);
//generate a new HttpClient using connection manager and parameters
mHttpClient = new DefaultHttpClient(mSCCmgr, mHttpParams);
}
public void setHTTPrequestListener(HTTPrequestListener httpRequestListener)
{
mHTTPrequestListener = httpRequestListener;
}
//other methods for POST and GET
}
当您想要下载文件时使用HTTPrequest httpRequest = new HTTPrequest(HttpVersion.HTTP_1_0);,当您想要执行POST 或GET 时使用HTTPrequest httpRequest = new HTTPrequest();