getContentLength()返回-1,在某些设备上,而不是其他
-
26-09-2019 - |
题
我想我之前下载获取文件的大小。我用conn.getContentLength();
做到这一点,它的作品在我的家用电脑的Android 2.1模拟器。
据然而,一旦我从我的手机(Wi-Fi或3G)运行我的应用程序,它也没有工作时,我从我的工作笔记本电脑的Android 2.1模拟器中运行它不工作。
有谁知道解决类似的问题?有另一种方法,我可以获取该文件的大小可能不使用HttpURLConnection
。
解决方案
此信息不会始终可用。通常你会知道你正在下载的文件的长度。根据不同的网络服务器,协议,连接,和下载的方法,该信息可能不总是可用的。
您一定要修改应用程序,以便它可以处理这种情况。我想你会使用不同的连接方法将提供与此不同的结果发现,不同的设备。
其他提示
使用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();
不隶属于 StackOverflow