Upload of Large File Using AndroidAsyncHttp Fails after sometime from android - android

I am trying to upload a file using AsyncHttpClient.Below is the code :
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");
}
}
}
this code works fine if the file upload takes very less time approx 1 min, But if the file size is greater and take more time . The AsyncHttpclient stops uploading File after some time without any error.
I have already tried with different setTimeOut .
Also there Is no error on server side. with Advanced rest client i have i am able to load any file size.
Thanks

Set
RequestParams data = new RequestParams();
if (file != null && file.exists())
data.put("Db_file", new FileInputStream(file));
data.setForceMultipartEntityContentType(true);
RequestParams class creates a non-buffered ByteArrayEntity to pass to the POST or PUT call, it is very easy to cause OutOfMemory errors with larger files, like when uploading a video or mp3 to a server, which are often larger than 4 or 5 MB.

Related

GET doesn't enter in methods onSucces and onFailure

I'm trying to do a get with AsyncHttpClient, but doesn't enter in both methods, in Postman it's going well, any idea what could be?
AsyncHttpClient client = new AsyncHttpClient();
String URL = "http://link/link1/link2";
client.get(URL, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
JSONArray dni;
String strResponseBody = new String(responseBody);
try {
dni = new JSONArray(strResponseBody);
for(int i=0; i < dni.length(); i ++){
dniTemporal = dni.getString(i);
Log.d("DNI : ",""+ dniTemporal );
}
} catch (JSONException e) {
Toast.makeText(JourneyDetails.this, "Error", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Log.d("ERROR STATUS:"," "+ statusCode);
}
});

How to upload all images stored in a file of internal memory

I need to send all images stored in a file. Now am sending one image on button click by specifying its name. But how to send all images on button click saved in some folder
public class UploadImagesToServer {
public static void postImage(String ImageLink){
RequestParams params = new RequestParams();
try {
params.put("file", new File(ImageLink));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
AsyncHttpClient mNewCaller = new AsyncHttpClient();
mNewCaller.get(Constants.MediaUpload, params, new JsonHttpResponseHandler() {
#Override
public void onStart() {
super.onStart();
}
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
Log.e("response page", response.toString());
}
#Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
super.onSuccess(statusCode, headers, responseString);
Log.e("frag", responseString + " " + statusCode);
}
#Override
public void onSuccess(int statusCode, Header[] headers, JSONArray responseString) {
super.onSuccess(statusCode, headers, responseString);
Log.e("frag", responseString + " " + statusCode);
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
super.onFailure(statusCode, headers, throwable, errorResponse);
Log.e("fail 3", statusCode + "" + errorResponse);
}
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
super.onFailure(statusCode, headers, responseString, throwable);
Log.e("fail 3", statusCode + "" + responseString);
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
super.onFailure(statusCode, headers, throwable, errorResponse);
Log.e("fail 3", statusCode + "" + errorResponse);
}
});
}
}
the above code is for sending an image
continueBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String filePath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + File.separator + "/Omoto Images/background image.jpg";
UploadImagesToServer.postImage(filePath);
}
});
this is for calling postImage method
Best process for uploading multiple images.
Your image uploading code already implemented you need to just change flow.
You could store your image paths in a list (or something similar) and save the
list (it may be shared preference or sqlite).
As you finish uploading a picture, remove it from that list and continue to the next one, and so on upto your list is empty.
When uploading, if the internet connection drops it will not affect you,
you will always have save the list of images that are still to be uploaded.
For get all images path:
You need to scan directory and store image path and before uploading check path file is exist or not because sometime image may be removed or move.

LoopJ AndroidAsyncHttp didn't go to onSuccess() or onFailure()

I used LoopJ AndroidAsyncHttp to get the response from the url, but the code didn't go into onSuccess() or onFailure(). The code is as below:
public void queryTopic(RequestParams params) {
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://192.168.0.109:8080/PhoneServer/topic/query", params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
System.out.println("It's in onSuccess");
}
// When the response returned by REST has Http response code
// other than '200'
#Override
public void onFailure(int statusCode, Throwable error,
String content) {
System.out.println("It's in onFailure");
}
});
System.out.println("It's over");
}
It just printed out the "It's over". What's the matter with the AsyncHttpClient?
How are you calling this? Is the context alive? If you are calling it from some place where context is no more available, then you will never get this callbacks.
I think you should try calling this queryTopic() method on click of some button and then wait for some time, you should get the response.
maybe the problem is that you ask to the server for a String
public void onSuccess(String response){...}
but server answer with a JSONObject
You can try this code:
AsyncHttpClient client = new AsyncHttpClient();
client.setTimeout(5000);
client.get(yourActivity.class, yourLink, new JsonHttpResponseHandler(){
#Override
public void onStart() {
Log.e(TAG, "start");
}
#Override
public void onSuccess(int status, Header[] headers, JSONObject answer) {
Log.e(TAG, "SUCCESS");
Log.e(TAG, "print => "+answer.getString("answer_id")); //"answer_id" is a random example
}
#Override
public void onFailure(int status, Header[] headers, String answer, Throwable throwable) {
Log.e(TAG, "FAILURE");
}
});
onSuccess() is an overloaded method be careful regarding what you send from server,
if it is a jsonObject or jsonArray or simple string. Use corresponding overloaded method of onSuccess(). I am using it too for a jsonObject response and i confront no error or irregularities in the method.
I return jsonObject from server for which my code works as expected and is as follows:
RequestParams params = new RequestParams();
params.put("pet","Cat");
params.put("name","Maran");
RestClient.get("/savelocation", params, new JsonHttpResponseHandler(){
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
Toast.makeText(context,response.toString(),Toast.LENGTH_SHORT).show();
Log.e("Error makerequest","request completed");
}
#Override
public void onFinish() {
//onLoginSuccess();
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable,JSONObject errorResponse){
Toast.makeText(context,throwable.toString(),Toast.LENGTH_LONG).show();
}
});
Note: RestClient is a static instance of AsyncHttpClient

Long polling issue: No response received

I have a issue and I need a help. I want to get updates from server via long polling. I'm using this library for server communication. https://github.com/loopj/android-async-http. Here is a code what I'm using
private void connectService() {
AsyncHttpClient httpClient = new AsyncHttpClient();
httpClient.setBasicAuth("key", "");
BaseJsonHttpResponseHandler handler = new BaseJsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, Object response) {
Log.e(TAG, "success body " + rawJsonResponse);
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData, Object errorResponse) {
Log.e(TAG, "error " + throwable.toString());
}
#Override
protected Object parseResponse(String rawJsonData, boolean isFailure) throws Throwable {
Log.e(TAG, "response body " + rawJsonData);
return null;
}
#Override
public void onPreProcessResponse(ResponseHandlerInterface instance, HttpResponse response) {
super.onPreProcessResponse(instance, response);
Log.e(TAG, "pre progress " + instance.getRequestURI());
}
};
httpClient.get(this, url, null, handler);
}
So I tested in browser and everything is work, but I didn't get any response on my device and also which library you is the best for using long polling?
Thanks

Posting image files to mediafire's upload resource using Android Asynchronous Http Client

I am trying to upload files from an Android application to Mediafire using their upload API resource. Also, I am using Android Asynchronous Http Client through out the app to handle the REST calls.
Problem:
The upload fails because of Mediafire returns code -99, "-99 : Missing or invalid session token".
I'm passing session_token along with 3 other parameters including the image file.
Here is the POST call:
RequestParams upload_params = new RequestParams();
File myFile = new File(image.getPath());
try {
upload_params.put("filename", myFile);
} catch(FileNotFoundException e) {
}
upload_params.put("session_token", session_token);
upload_params.put("uploadkey", MyConstants.MEDIA_FOLDER_KEY);
upload_params.put("response_format", MyConstants.MEDIA_RESPONSE_FORMAT);
Log.d("PARAMS: ", upload_params.toString());
client.post(MyConstants.MEDIA_BASE_URL + MyConstants.MEDIA_UPLOAD, upload_params, new JsonHttpResponseHandler() {
#Override
public void onStart() {
}
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
String response_string = new String(response);
Log.d("RESPONSE: ", response_string);
Log.d("SESSION_TOKEN: ", session_token);
Log.d("STATUS CODE: ", Integer.toString(statusCode));
for(int i = 0; i < headers.length; i++) {
Log.d("Header " + i + ": ", headers[i].toString());
}
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
}
});
I don't know why but I think my session_token, uploadkey and response_format are not being sent because when I look at the logcat I see the response I get back from Mediafire is in XML.
Any help will be greatly appreciated! Let me know if more information is needed.
So after countless hours of debugging (3 days worth) that lead no where I finally figured out why the upload wouldn't go through.
Basically Mediafire requires only the file as the POST parameter. It expects the session_token, uploadkey and other parameters as GET.
I changed my upload_params and POST request to the following to get it working:
RequestParams upload_params = new RequestParams();
File myFile = new File(image.getPath());
try {
upload_params.put("filename", myFile);
} catch(FileNotFoundException e) {
}
client.post(MyConstants.MEDIA_BASE_URL + MyConstants.MEDIA_UPLOAD +
"?session_token=my_session_token" +
"&uploadkey=" + MyConstants.MEDIA_FOLDER_KEY +
"&response_format=" + MyConstants.MEDIA_RESPONSE_FORMAT),
upload_params,
new JsonHttpResponseHandler() {
#Override
public void onStart() {
}
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
Log.d("RESPONSE: ", new String(response));
Log.d("SESSION_TOKEN: ", session_token);
Log.d("STATUS CODE: ", Integer.toString(statusCode));
for(int i = 0; i < headers.length; i++) {
Log.d("Header " + i + ": ", headers[i].toString());
}
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
}
});

Categories

Resources