Skip to content Skip to sidebar Skip to footer

Network Request Doesn't Work When Uploading A File

I am facing a problem which I don't know how to solve. GetDataTask works fine. But when I am uploading a file, the request is sent but the response comes only after the file uploa

Solution 1:

Ok following are the notes from the official java doc...

Order of execution

When first introduced, AsyncTasks were executed serially on a single background thread. Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution.

If you truly want parallel execution, you can invoke executeOnExecutor(java.util.concurrent.Executor, Object[]) with THREAD_POOL_EXECUTOR.

SO if you invoke two AsyncTask together.. they would not be executed in parallel (exception is donut, ECLAIR and gingerbread)... You can use executeOnExecutor to execute them in parallel...

Solution 2:

try like this,

package com.file.upload;

import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;

import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;

publicclassCustomMultiPartEntityextendsMultipartEntity{

    privatefinal ProgressListener listener;

    publicCustomMultiPartEntity(final ProgressListener listener)
    {
        super();
        this.listener = listener;
    }

    publicCustomMultiPartEntity(final HttpMultipartMode mode, final ProgressListener listener)
    {
        super(mode);
        this.listener = listener;
    }

    publicCustomMultiPartEntity(HttpMultipartMode mode, final String boundary, final Charset charset, final ProgressListener listener)
    {
        super(mode, boundary, charset);
        this.listener = listener;
    }

    @OverridepublicvoidwriteTo(final OutputStream outstream)throws IOException
    {
        super.writeTo(newCountingOutputStream(outstream, this.listener));
    }

    publicstaticinterfaceProgressListener
    {
        voidtransferred(long num);
    }

    publicstaticclassCountingOutputStreamextendsFilterOutputStream
    {

        privatefinal ProgressListener listener;
        privatelong transferred;

        publicCountingOutputStream(final OutputStream out, final ProgressListener listener)
        {
            super(out);
            this.listener = listener;
            this.transferred = 0;
        }

        publicvoidwrite(byte[] b, int off, int len)throws IOException
        {
            out.write(b, off, len);
            this.transferred += len;
            this.listener.transferred(this.transferred);
        }

        publicvoidwrite(int b)throws IOException
        {
            out.write(b);
            this.transferred++;
            this.listener.transferred(this.transferred);
        }
    }
}

This is HttpMultipartPost .java to upload file

import java.io.File;
    import java.io.IOException;
    import org.apache.http.HttpResponse;
    import org.apache.http.HttpStatus;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.mime.MultipartEntity;
    import org.apache.http.entity.mime.content.ContentBody;
    import org.apache.http.entity.mime.content.FileBody;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.params.BasicHttpParams;
    import org.apache.http.params.HttpConnectionParams;
    import org.apache.http.params.HttpParams;
    import org.apache.http.util.EntityUtils;
    import com.file.upload.MyMultipartEntity.ProgressListener;
    import android.app.ProgressDialog;
    import android.content.Context;
    import android.os.AsyncTask;
    import android.util.Log;

        publicclassHttpMultipartPostextendsAsyncTask<Void, Integer, Void> {

            private Context context;
            private String filepath;

            private HttpClient client;

            private ProgressDialog pd;
            privatelong totalSize;

            privatestaticfinalStringurl="Your URL";

            publicHttpMultipartPost(Context context, String filepath) {
                super();
                this.context = context;
                this.filepath= filepath;
            }

            @OverrideprotectedvoidonPreExecute() {
                //Set timeout parametersinttimeout=10000;
                HttpParamshttpParameters=newBasicHttpParams();
                HttpConnectionParams.setConnectionTimeout(httpParameters, timeout);
                HttpConnectionParams.setSoTimeout(httpParameters, timeout);

                //We'll use the DefaultHttpClient
                client = newDefaultHttpClient(httpParameters);

                pd = newProgressDialog(context);
                pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                pd.setMessage("Uploading File...");
                pd.setCancelable(false);
                pd.show();
            }

            @Overrideprotected Void doInBackground(Void... params) {
                try {
                    Filefile=newFile(filepath);

                    //Create the POST objectHttpPostpost=newHttpPost(url);

                    //Create the multipart entity object and add a progress listener//this is a our extended class so we can know the bytes that have been transferedMultipartEntityentity=newCustomMultiPartEntity (newProgressListener()
                    {
                        @Overridepublicvoidtransferred(long num)
                        {
                            //Call the onProgressUpdate method with the percent completed
                            publishProgress((int) ((num / (float) totalSize) * 100));
                            Log.d("DEBUG", num + " - " + totalSize);
                        }
                    });
                    //Add the file to the content's bodyContentBodycbFile=newFileBody( file, "image/jpeg" );// change according
                    entity.addPart("source", cbFile);

                    //After adding everything we get the content's lenght
                    totalSize = entity.getContentLength();

                    //We add the entity to the post request
                    post.setEntity(entity);

                    //Execute post requestHttpResponseresponse= client.execute( post );
                    intstatusCode= response.getStatusLine().getStatusCode();

                    if(statusCode == HttpStatus.SC_OK){
                        //If everything goes ok, we can get the responseStringfullRes= EntityUtils.toString(response.getEntity());
                        Log.d("DEBUG", fullRes);

                    } else {
                        Log.d("DEBUG", "HTTP Fail, Response Code: " + statusCode);
                    }

                } catch (ClientProtocolException e) {
                    // Any error related to the Http Protocol (e.g. malformed url)
                    e.printStackTrace();
                } catch (IOException e) {
                    // Any IO error (e.g. File not found)
                    e.printStackTrace();
                }


                returnnull;
            }

            @OverrideprotectedvoidonProgressUpdate(Integer... progress) {
                //Set the pertange done in the progress dialog
                pd.setProgress((int) (progress[0]));
            }

            @OverrideprotectedvoidonPostExecute(Void result) {
                //Dismiss progress dialog
                pd.dismiss();
            }

        }


Hope this will helpful to you. 

Solution 3:

Things work fine when I replace GetData Task by a simple thread.

newThread( newRunnable() {

            @Overridepublicvoidrun() {
                String res = NetConnection. getRecordData(mUserId, mUserPassword);
                Log.e(TAG, res);
                parseJson(res);

            }
        }).start();

There is something fishy with AsyncTask and I dont know why.

Post a Comment for "Network Request Doesn't Work When Uploading A File"