我正在尝试使用AsyncHttpClient上传一个文件。下面是代码:
public class uploadVideoAsyncTask extends AsyncTask<String,Void,JSONObject>{
Context context;
SyncHttpClient client;
JSONObject response;
public uploadVideoAsyncTask(Context context) {
this.context = context;
}
@Override
protected JSONObject doInBackground(String... params) {
if(client != null){
RequestParams data = new RequestParams();
File video = new File(params[0]);
try {
data.put("upload", video, "video/*");
Log.d("debug", LoginActivity.URL + LoginActivity.URL_UPLOAD_VIDEO);
client.post(LoginActivity.URL+LoginActivity.URL_UPLOAD_VIDEO,data,new JsonHttpResponseHandler(){
@Override
public void onProgress(long bytesWritten, long totalSize) {
super.onProgress(bytesWritten, totalSize);
Log.d("debug",bytesWritten +" "+ totalSize);
}
@Override
public void onUserException(Throwable error) {
super.onUserException(error);
Log.d("debug",error.toString());
}
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
Log.d("debug", response.toString());
initializeResponse(response);
}
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
super.onFailure(statusCode, headers, throwable, errorResponse);
Log.d("debug", errorResponse.toString());
initializeResponse(errorResponse);
}
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
super.onFailure(statusCode, headers, responseString, throwable);
Log.d("debug", responseString);
initializeResponse(null);
}
});
} catch (FileNotFoundException e) {
e.printStackTrace();
initializeResponse(null);
}
}else{
initializeResponse(null);
}
return this.response;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
initializeHttpClient();
}
@Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
Log.d("debug","ererr");
}
private void initializeResponse(JSONObject response){
this.response = response;
}
private void initializeHttpClient(){
if(client == null){
client = new SyncHttpClient();
//client.setMaxRetriesAndTimeout(LoginActivity.maxRetries, LoginActivity.TIME_OUT);
client.setTimeout(50000);
Log.d("debug", client.getResponseTimeout() + "");
Log.d("debug", client.getConnectTimeout()+"");
client.addHeader("x-access-token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiI1NzFiOTBmOTM4ZmQ1NzA4MGUzMTY1Y2IifQ.2l4DVRTVhxFnD796M5CPIEloGW6N-qBnXxa3lC0XDRU");
//client.addHeader("Content-Type", " application/json");
}
}
}
如果文件上传所需的时间非常短,大约1分钟,这个代码可以正常工作,但如果文件大小更大,需要更多的时间。AsyncHttpclient在一段时间后停止上载文件,没有任何错误。
我已经尝试了不同的setTimeOut。服务器端也没有错误。有了高级休息客户端,我可以加载任何文件大小。
感谢
Set
RequestParams data = new RequestParams();
if (file != null && file.exists())
data.put("Db_file", new FileInputStream(file));
data.setForceMultipartEntityContentType(true);
RequestParams类创建一个非缓冲的ByteArrayEntity以传递给POST或PUT调用,对于较大的文件,很容易导致OutOfMemory错误,比如将视频或mp3上传到服务器时,这些文件通常大于4或5 MB。