上传文件时,网络请求不起作用 [英] Network request doesn't work when uploading a file

查看:217
本文介绍了上传文件时,网络请求不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

结果
我面对,我不知道如何解决的一个问题。结果
GetDataTask工作正常。但是,当我上传文件,发送请求但响应自带文件上传完毕后,才! GetDataTask和UploadTask异步运行使用AsyncTask的。结果
任何想法,为什么它不工作以及为什么反应不回来当文件被上传。结果
有没有意识到这一点?结果的另一种方式
问题是,它应该在并行运行但不幸的是他们同步运行。结果
下面我贴我的实际来源。结果
先谢谢了。

的GetData任务

 私有类GetDataTask扩展的AsyncTask<弦乐,太虚,字符串> {    @覆盖
    在preExecute保护无效(){    }    @覆盖
    保护字符串doInBackground(字符串... PARAMS){
        返回NetConnection.getRecordData(mUserId,mUserPassword);
    }    @覆盖
    保护无效onPostExecute(字符串结果){
        parseJson(结果);
    }
}

上传任务

 私有类HttpMultipartPost扩展的AsyncTask<字符串,整数,字符串>
    {
        TextProgressBar PB;
        长总计TOTALSIZE;
        字符串文件路径;        @覆盖
        在preExecute保护无效()
        {
            PB =(TextProgressBar)findViewById(R.id.idPBUploadProgress);
            pb.setMax(100);
        }        @覆盖
        保护字符串doInBackground(字符串... ARG)
        {
            HttpClient的HttpClient的=新DefaultHttpClient();
            HttpContext的HttpContext的=新BasicHttpContext();
            HttpPost httpPost =新HttpPost(Utils.UPLOAD_URL);            尝试
            {
                CustomMultiPartEntity multipartContent =新CustomMultiPartEntity(新ProgressListener()
                {
                    @覆盖
                    公共无效转移(长NUM)
                    {
                        publishProgress((INT)((NUM /(浮点)总计TOTALSIZE)* 100));
                        //Log.v(TAG,进步=+ NUM);
                    }
                });                //我们使用FileBody传输一个文件
                文件路径=精氨酸[0];
                multipartContent.addPart(upfile,新FileBody(新文件(文件路径)));
                总计TOTALSIZE = multipartContent.getContentLength();
                Log.e(TAG上传文件大小=+总计TOTALSIZE / 1048576 +MB);                // 发送
                httpPost.setEntity(multipartContent);
                HTT presponse响应= httpClient.execute(httpPost,HttpContext的);
                串serverResponse = EntityUtils.toString(response.getEntity());                返回serverResponse;
            }            赶上(例外五)
            {
                的System.out.println(E);
            }
            返回null;
        }        @覆盖
        保护无效onProgressUpdate(整数...进度)
        {
            pb.setProgress((int)的(进步[0]));
            pb.setText(进展[0] +%);
        }        @覆盖
        保护无效onPostExecute(字符串结果)
        {
            Log.e(TAG,响应=+结果);
            parseResult(因此,文件路径);
        }
    }


解决方案

好以下是笔记从的官方JAVA DOC ...


  

执行顺序


  
  

在首次推出,AsyncTasks被连续在一个执行
  后台线程。与 DONUT 开始,这是改变到
  线程允许多个任务,以在并行地操作的池。
  与蜂窝开始,任务的执行在单个线程来
  避免因并行执行常见的应用程序错误。


  
  

如果你真正想要的并行执行,你可以调用
  <一href=\"http://developer.android.com/reference/android/os/AsyncTask.html#executeOnExecutor%28java.util.concurrent.Executor,%20Params...%29\"相对=nofollow> executeOnExecutor(java.util.concurrent.Executor,对象[])与
   THREAD_POOL_EXECUTOR


所以,如果你调用2的AsyncTask在一起..他们不会被并行执行(异常甜甜圈,ECLAIR和姜饼)...你可以使用 executeOnExecutor 执行他们在并行...


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 upload is finished! GetDataTask and UploadTask run asynchronously using AsyncTask.
Any idea why it doesn't work and why the response doesn't come back when the file is uploading.
Is there another way to realize this?
The problem is, it is supposed to run in a parallel but unfortunately they are running synchronously.
I have posted my actual source below.
Thanks in advance.

GetData Task:

private class GetDataTask extends AsyncTask<String, Void, String>{

    @Override
    protected void onPreExecute() {

    }

    @Override
    protected String doInBackground(String... params) {
        return NetConnection.getRecordData(mUserId, mUserPassword);
    }

    @Override
    protected void onPostExecute(String result) {
        parseJson(result);
    }
}

Upload Task:

    private class HttpMultipartPost extends AsyncTask<String, Integer, String>
    {
        TextProgressBar pb;
        long totalSize;
        String filePath;

        @Override
        protected void onPreExecute()
        {
            pb = (TextProgressBar) findViewById(R.id.idPBUploadProgress);
            pb.setMax(100);
        }

        @Override
        protected String doInBackground(String... arg)
        {
            HttpClient httpClient = new DefaultHttpClient();
            HttpContext httpContext = new BasicHttpContext();
            HttpPost httpPost = new HttpPost( Utils.UPLOAD_URL );

            try
            {
                CustomMultiPartEntity multipartContent = new CustomMultiPartEntity(new ProgressListener()
                {
                    @Override
                    public void transferred(long num)
                    {
                        publishProgress((int) ((num / (float) totalSize) * 100));
                        //Log.v(TAG, "Progress =" + num);
                    }
                });

                // We use FileBody to transfer an file
                filePath = arg[0];
                multipartContent.addPart("upfile", new FileBody(new File( filePath )));
                totalSize = multipartContent.getContentLength();
                Log.e(TAG, "Upload file size = " + totalSize/1048576 + "MB") ;

                // Send it
                httpPost.setEntity(multipartContent);
                HttpResponse response = httpClient.execute(httpPost, httpContext);
                String serverResponse = EntityUtils.toString(response.getEntity());

                return serverResponse;
            }

            catch (Exception e)
            {
                System.out.println(e);
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... progress)
        {
            pb.setProgress((int) (progress[0]));
            pb.setText(progress[0] + "%");
        }

        @Override
        protected void onPostExecute(String result)
        {
            Log.e(TAG, "Response =" + result);
            parseResult( result, filePath );
        }
    }

解决方案

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...

这篇关于上传文件时,网络请求不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆