我正在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();
}
}
答案 0 :(得分:0)
您可以尝试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( );
}