[英]How can I improve the file upload speed for big size?
我正在 Android 操作系統上開發文件上傳應用程序。
基本上我正在使用 HttpURLConnection 並且它是必需的。
大約相同的文件大小,IOS 非常快,我使用了 AFNetworking。
但是Android太慢了,請指教我所缺少的。
這是我使用的源代碼。
謝謝你。
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection)(new URL(url)).openConnection();
conn.setRequestMethod("PUT");
conn.setReadTimeout(3600*1000);
conn.setRequestProperty("Content-Type", "application/octet-stream");
File temp = new File(file_path);
int length = (int)temp.length();
conn.setFixedLengthStreamingMode(length);
conn.setUseCaches (false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Authorization", "xxx");
conn.connect();
OutputStream out = new DataOutputStream(conn.getOutputStream());
InputStream in = new FileInputStream(file_path);
int bytesAvailable = in.available();
int maxBufferSize = 1024 * 300;
int totalSize = bytesAvailable;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];
long bytesRead = in.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
out.write(buffer, 0, bufferSize);
bytesAvailable = in.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = in.read(buffer, 0, bufferSize);
}
out.flush();
out.close();
in.close();
InputStream is = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
rd.close();
is.close();
} catch (Exception e) {
return false;
} finally {
if(conn != null) {
conn.disconnect();
}
}
您可以嘗試HttpClient jar下載最新的 HttpClient jar,將其添加到您的項目中,並使用以下方法上傳文件:
private void uploadFile(String filePath) throws ParseException, IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(YOUR_URL);
FileBody filebodyVideo = new FileBody(new File(filePath));
StringBody title = new StringBody("Filename: " + filePath);
StringBody description = new StringBody("This is a video of the agent");
StringBody code = new StringBody(realtorCodeStr);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("filePath", filebodyVideo);
reqEntity.addPart("title", title);
reqEntity.addPart("description", description);
reqEntity.addPart("code", code);
httppost.setEntity(reqEntity);
// DEBUG
System.out.println( "executing request " + httppost.getRequestLine( ) );
HttpResponse response = httpclient.execute( httppost );
HttpEntity resEntity = response.getEntity( );
// DEBUG
System.out.println( response.getStatusLine( ) );
if (resEntity != null) {
System.out.println( EntityUtils.toString( resEntity ) );
} // end if
if (resEntity != null) {
resEntity.consumeContent( );
} // end if
httpclient.getConnectionManager( ).shutdown( );
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.