0

我正在尝试使用 Asynctask 将文件上传到 PHP 服务器,但由于出现错误而无法上传。这是日志:

04-03 00:52:16.065: I/Process(11648): Sending signal. PID: 11648 SIG: 9
04-03 00:52:28.955: I/URL FORMATION(11752): MALFORMATED URL
04-03 00:52:28.955: E/3rd(11752): Starting to bad things
04-03 00:52:28.963: W/dalvikvm(11752): threadid=11: thread exiting with uncaught exception (group=0x4195f2a0)
04-03 00:52:28.963: E/AndroidRuntime(11752): FATAL EXCEPTION: AsyncTask #1
04-03 00:52:28.963: E/AndroidRuntime(11752): java.lang.RuntimeException: An error occured while executing 

doInBackground()
04-03 00:52:28.963: E/AndroidRuntime(11752):    at android.os.AsyncTask$3.done(AsyncTask.java:299)
04-03 00:52:28.963: E/AndroidRuntime(11752):    at java.util.concurrent.FutureTask$Sync.innerSetException

(FutureTask.java:273)
04-03 00:52:28.963: E/AndroidRuntime(11752):    at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
04-03 00:52:28.963: E/AndroidRuntime(11752):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
04-03 00:52:28.963: E/AndroidRuntime(11752):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
04-03 00:52:28.963: E/AndroidRuntime(11752):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
04-03 00:52:28.963: E/AndroidRuntime(11752):    at java.util.concurrent.ThreadPoolExecutor.runWorker

(ThreadPoolExecutor.java:1076)
04-03 00:52:28.963: E/AndroidRuntime(11752):    at java.util.concurrent.ThreadPoolExecutor$Worker.run

(ThreadPoolExecutor.java:569)
04-03 00:52:28.963: E/AndroidRuntime(11752):    at java.lang.Thread.run(Thread.java:856)
04-03 00:52:28.963: E/AndroidRuntime(11752): Caused by: java.lang.NullPointerException
04-03 00:52:28.963: E/AndroidRuntime(11752):    at com.example.up.HttpFileUploader.thirdTry(HttpFileUploader.java:54)
04-03 00:52:28.963: E/AndroidRuntime(11752):    at com.example.up.HttpFileUploader.doStart(HttpFileUploader.java:36)
04-03 00:52:28.963: E/AndroidRuntime(11752):    at com.example.up.MainActivity.uploadFile(MainActivity.java:59)
04-03 00:52:28.963: E/AndroidRuntime(11752):    at com.example.up.MainActivity$myasynctask.doInBackground

(MainActivity.java:38)
04-03 00:52:28.963: E/AndroidRuntime(11752):    at com.example.up.MainActivity$myasynctask.doInBackground

(MainActivity.java:1)
04-03 00:52:28.963: E/AndroidRuntime(11752):    at android.os.AsyncTask$2.call(AsyncTask.java:287)
04-03 00:52:28.963: E/AndroidRuntime(11752):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
04-03 00:52:28.963: E/AndroidRuntime(11752):    ... 5 more
04-03 00:52:29.182: D/libEGL(11752): loaded /vendor/lib/egl/libEGL_POWERVR_SGX540_120.so
04-03 00:52:29.182: D/libEGL(11752): loaded /vendor/lib/egl/libGLESv1_CM_POWERVR_SGX540_120.so
04-03 00:52:29.190: D/libEGL(11752): loaded /vendor/lib/egl/libGLESv2_POWERVR_SGX540_120.so
04-03 00:52:29.284: D/OpenGLRenderer(11752): Enabling debug mode 0
04-03 00:52:35.518: I/Choreographer(11752): Skipped 375 frames!  The application may be doing too much work on its main 

thread.
04-03 00:52:35.768: E/WindowManager(11752): Activity com.example.up.MainActivity has leaked window 

com.android.internal.policy.impl.PhoneWindow$DecorView@42138c08 that was originally added here
04-03 00:52:35.768: E/WindowManager(11752): android.view.WindowLeaked: Activity com.example.up.MainActivity has leaked 

window com.android.internal.policy.impl.PhoneWindow$DecorView@42138c08 that was originally added here
04-03 00:52:35.768: E/WindowManager(11752):     at android.view.ViewRootImpl.<init>(ViewRootImpl.java:397)
04-03 00:52:35.768: E/WindowManager(11752):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:311)
04-03 00:52:35.768: E/WindowManager(11752):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224)
04-03 00:52:35.768: E/WindowManager(11752):     at android.view.WindowManagerImpl$CompatModeWrapper.addView

(WindowManagerImpl.java:149)
04-03 00:52:35.768: E/WindowManager(11752):     at android.view.Window$LocalWindowManager.addView(Window.java:556)
04-03 00:52:35.768: E/WindowManager(11752):     at android.app.Dialog.show(Dialog.java:277)
04-03 00:52:35.768: E/WindowManager(11752):     at com.example.up.MainActivity$myasynctask.onPreExecute

(MainActivity.java:32)
04-03 00:52:35.768: E/WindowManager(11752):     at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
04-03 00:52:35.768: E/WindowManager(11752):     at android.os.AsyncTask.execute(AsyncTask.java:534)
04-03 00:52:35.768: E/WindowManager(11752):     at com.example.up.MainActivity.onCreate(MainActivity.java:20)
04-03 00:52:35.768: E/WindowManager(11752):     at android.app.Activity.performCreate(Activity.java:5163)
04-03 00:52:35.768: E/WindowManager(11752):     at android.app.Instrumentation.callActivityOnCreate

(Instrumentation.java:1094)
04-03 00:52:35.768: E/WindowManager(11752):     at android.app.ActivityThread.performLaunchActivity

(ActivityThread.java:2061)
04-03 00:52:35.768: E/WindowManager(11752):     at android.app.ActivityThread.handleLaunchActivity

(ActivityThread.java:2122)
04-03 00:52:35.768: E/WindowManager(11752):     at android.app.ActivityThread.access$600(ActivityThread.java:140)
04-03 00:52:35.768: E/WindowManager(11752):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1228)
04-03 00:52:35.768: E/WindowManager(11752):     at android.os.Handler.dispatchMessage(Handler.java:99)
04-03 00:52:35.768: E/WindowManager(11752):     at android.os.Looper.loop(Looper.java:137)
04-03 00:52:35.768: E/WindowManager(11752):     at android.app.ActivityThread.main(ActivityThread.java:4895)
04-03 00:52:35.768: E/WindowManager(11752):     at java.lang.reflect.Method.invokeNative(Native Method)
04-03 00:52:35.768: E/WindowManager(11752):     at java.lang.reflect.Method.invoke(Method.java:511)
04-03 00:52:35.768: E/WindowManager(11752):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run

(ZygoteInit.java:994)
04-03 00:52:35.768: E/WindowManager(11752):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:761)
04-03 00:52:35.768: E/WindowManager(11752):     at dalvik.system.NativeStart.main(Native Method)

为了上传文件,我有 2 个类:HTTPFileUploader:

public class HttpFileUploader implements Runnable{

    URL connectURL;
    String params;
    String responseString;
    //InterfaceHttpUtil ifPostBack;
    String fileName;
    byte[] dataToServer;

    HttpFileUploader(String urlString, String params, String fileName ){
        try{
            connectURL = new URL(urlString);
        }catch(Exception ex){
            Log.i("URL FORMATION","MALFORMATED URL");
        }
        this.params = params+"=";
        this.fileName = fileName;
    }


    void doStart(FileInputStream stream){ 
        fileInputStream = stream;
        thirdTry();
    } 

    FileInputStream fileInputStream = null;
    void thirdTry() {
        String exsistingFileName = fileName;

        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        String Tag="3rd";
        try
        {
            //------------------ CLIENT REQUEST

            Log.e(Tag,"Starting to bad things");
            // Open a HTTP connection to the URL

            HttpURLConnection conn = (HttpURLConnection) connectURL.openConnection();

            // Allow Inputs
            conn.setDoInput(true);

            // Allow Outputs
            conn.setDoOutput(true);

            // Don't use a cached copy.
            conn.setUseCaches(false);

            // Use a post method.
            conn.setRequestMethod("POST");

            conn.setRequestProperty("Connection", "Keep-Alive");

            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

            DataOutputStream dos = new DataOutputStream( conn.getOutputStream() );

            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + exsistingFileName +"\"" + lineEnd);
            dos.writeBytes(lineEnd);




            Log.e(Tag,"Headers are written");

            // create a buffer of maximum size

            int bytesAvailable = fileInputStream.available();
            int maxBufferSize = 1024;
            int bufferSize = Math.min(bytesAvailable, maxBufferSize);
            byte[] buffer = new byte[bufferSize];

            // read file and write it into form...

            int bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            while (bytesRead > 0)
            {
            dos.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            }

            // send multipart form data necesssary after file data...

            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            // close streams
            Log.e(Tag,"File is written");
            fileInputStream.close();
            dos.flush();

            InputStream is = conn.getInputStream();
            // retrieve the response from server
            int ch;

            StringBuffer b =new StringBuffer();
            while( ( ch = is.read() ) != -1 ){
            b.append( (char)ch );
            }
            String s=b.toString(); 
            Log.i("Response",s);
            dos.close();


        }
        catch (MalformedURLException ex)
        {
            Log.e(Tag, "error: " + ex.getMessage(), ex);
        }

        catch (IOException ioe)
        {
            Log.e(Tag, "error: " + ioe.getMessage(), ioe);
        }
    }


@Override
public void run() {

}

}

MainActivity,其中 Asynctask 在开始时执行,应该从 sdcard 上传文件。

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        new myasynctask().execute();

    }


    public class myasynctask extends AsyncTask<Void, Void, Void>{
        private final ProgressDialog dialog = new ProgressDialog(
                MainActivity.this);

        protected void onPreExecute() {
            this.dialog.setMessage("Loading...");
            this.dialog.setCancelable(false);
            this.dialog.show();
        }
            @Override
            protected Void doInBackground(Void... params) {

                File sdCard = Environment.getExternalStorageDirectory();
                uploadFile(sdCard.getAbsolutePath() + "/PruebasEvaluacion/text.txt");
                return null;
            }

            protected void onPostExecute(Void result) {

                // Here if you wish to do future process for ex. move to another activity do here

                if (dialog.isShowing()) {
                    dialog.dismiss();
                }

            }
        }


       public void uploadFile(String filename){
            try {
                //FileInputStream fis =this.openFileInput(filename);
                FileInputStream fis = new FileInputStream(filename);
                HttpFileUploader htfu = new HttpFileUploader("192.168.1.37/prueba/upload_file.php","noparamshere", filename);
                htfu.doStart(fis);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }


}

我希望一切都清楚,如果有不清楚的地方,我会回答一切。感谢您的时间和耐心。

4

1 回答 1

0

您对以下行有疑问

HttpURLConnection conn = (HttpURLConnection) connectURL.openConnection();

这是因为您试图打开与格式错误的 URL 的连接

如果您查看日志猫,您将看到以下行

04-03 00:52:28.955: I/URL FORMATION(11752): MALFORMATED URL

发生这种情况是因为您在创建URL时没有定义协议。

HttpFileUploader htfu = new HttpFileUploader("192.168.1.37/prueba/upload_file.php","noparamshere", filename);

根据您的要求添加 Http 或 ftp。

于 2013-04-03T00:53:01.140 回答