setFixedLengthStreamingMode

setFixedLengthStreamingMode

我试图在fixedLengthStreamingMode()对象中设置HttpURLConnection属性,但出现异常java.lang.NoSuchMethodError


码:

FileInputStream fileInputStream = new FileInputStream(
                    sourceFile);
            String url = this.fileParameter.getServerUrl();
            conn = getMultipartHttpURLConnection(url, boundary);
            String header=setRequestHeaders(conn);
            conn.setRequestProperty(this.fileParameter.getFileKey(),
                    this.fileParameter.getFileName());
            requestSize= (header.length()+new File(fileParameter.getFilePath()).length());
            conn.setFixedLengthStreamingMode(requestSize);


错误

E/AndroidRuntime(17418): java.lang.RuntimeException: An error occured while executing doInBackground()

 E/AndroidRuntime(17418): Caused by: java.lang.NoSuchMethodError: java.net.HttpURLConnection.setFixedLengthStreamingMode


注意:我正在使用java 7 platform。

最佳答案

在此处查看文档https://developer.android.com/reference/java/net/HttpURLConnection.html#setFixedLengthStreamingMode(int)

有两种方法:


setFixedLengthStreamingMode(int)Added in API level 1
setFixedLengthStreamingMode(long)Added in API level 19


int最大值是2,147,483,647

long最大值是9,223,372,036,854,775,807

流式术语,这意味着setFixedLengthStreamingMode(int)的最大大小长度为(为安全起见,删除了小数):

int sizeInBytes = Integer.MAX_VALUE; // 2,147,483,647 bytes
int sizeInKB = sizeInBytes / 1024;   // 2,097,151 kilobytes
int sizeInMB = sizeInKB / 1024;      // 2,047 megabytes
int sizeInGB = sizeInMB / 1024;      // 1.99 gigabytes


API 19中添加的setFixedLengthStreamingMode(long)支持的大小大于Integer.Max的能力(即大文件):

long sizeInBytes = Long.MAX_VALUE;  // 9,223,372,036,854,775,807 bytes
long sizeInKB = sizeInBytes / 1024; // 9,007,119,254,740,991 kilobytes
long sizeInMB = sizeInKB / 1024;    // 8,796,014,897,207 megabytes
long sizeInGB = sizeInMB / 1024;    // 8,589,858,298 gigabytes
long sizeInTB = sizeInGB / 1024;    // 8,388,533 terabytes
long sizeInPB = sizeInTB / 1024;    // 8,191 petabytes


如果您永远不会超过Integer.MAX_VALUE,则将您的long contentLength强制转换为int,并且不会出现API错误,但是在requestSize > Integer.MAX_VALUE时会出现错误:

conn.setFixedLengthStreamingMode((int) requestSize);


您可以简单地执行以下操作:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    conn.setFixedLengthStreamingMode(requestSize);
} else if (requestSize <= Integer.MAX_VALUE) {
    conn.setFixedLengthStreamingMode((int) requestSize);
} else {
    //Don't set fixed length...
}

关于java - 在HttpURLConnection.setFixedLengthSTreamingMode()中获取异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27793247/

10-10 05:13