我正在尝试在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平台。
答案 0 :(得分:0)
有两种方法:
Added in API level 1
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...
}