簡體   English   中英

getContentLength()在某些設備而非其他設備上返回-1

[英]getContentLength() returning -1 on some devices and not others

我正在嘗試獲取文件的大小,然后再下載它。 我使用conn.getContentLength(); 為此,它可以在我的家用計算機Android 2.1 Emulator上正常運行。

但是,一旦我通過手機(WiFi或3G)運行我的應用程序,該功能將無法使用,而當我從工作筆記本電腦的Android 2.1仿真器中運行該應用程序時,該功能也將無法使用。

有誰知道解決方法? 還有另一種方法可以獲取文件的大小,而無需使用HttpURLConnection

此信息並非始終可用。 通常,您會知道要下載的文件的長度。 根據Web服務器,協議,連接和下載方法的不同,此信息可能並不總是可用。

您絕對應該修改您的應用程序,以便它可以處理這種情況。 我認為您會發現使用不同連接方法的不同設備將為此提供不同的結果。

使用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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM