簡體   English   中英

將文本文件從android上傳到服務器,出現錯誤

[英]uploading a text file from android to server , getting Error

這是我在android中上傳文件的代碼。

       HttpURLConnection conn = null;
    DataOutputStream dos = null;
    DataInputStream inStream = null;
    String existingFileName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Bluetooth/my.txt";
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    String responseFromServer = "";
    String urlString ="http://172.20.56.36:8084/AndroidTesting/UploadServlet.java";


    try {


        FileInputStream fileInputStream = new FileInputStream(new File(existingFileName));

        URL url = new URL(urlString);

        conn = (HttpURLConnection) url.openConnection();

        conn.setDoInput(true);

        conn.setDoOutput(true);

        conn.setUseCaches(false);

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
     dos = new DataOutputStream(conn.getOutputStream());
        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + existingFileName + "\"" + lineEnd);
        dos.writeBytes(lineEnd);

        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];
        // read file and write it into form...
        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("Debug", "File is written");
        fileInputStream.close();
        dos.flush();
        dos.close();

    } catch(Exception e){
        Toast.makeText(getApplicationContext(),e.getMessage()+"error",Toast.LENGTH_SHORT).show();
    }




    //------------------ read the SERVER RESPONSE
    try {

        inStream = new DataInputStream(conn.getInputStream());
        String str;

         while ((str = inStream.readLine()) != null) {

               Toast.makeText(getApplicationContext(),str,Toast.LENGTH_SHORT).show();
          }

        inStream.close();

    } catch (Exception ioex) {

      Toast.makeText(getApplicationContext(),ioex.getMessage()+"error",Toast.LENGTH_SHORT).show();
    }
 }

因此,當我運行此應用程序時,它崩潰了,然后放入了try catch塊,然后出現了空錯誤,並且我認為它在這一行中

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

Logcat報告

06-23 12:02:50.159: D/AndroidRuntime(5832): Shutting down VM
06-23 12:02:50.169: W/dalvikvm(5832): threadid=1: thread exiting with uncaught   exception (group=0x40c1aa68)
06-23 12:02:50.169: E/AndroidRuntime(5832): FATAL EXCEPTION: main
06-23 12:02:50.169: E/AndroidRuntime(5832): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.e.testing/com.e.testing.MainActivity}:          android.os.NetworkOnMainThreadException
06-23 12:02:50.169: E/AndroidRuntime(5832):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1970)
06-23 12:02:50.169: E/AndroidRuntime(5832):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1995)
06-23 12:02:50.169: E/AndroidRuntime(5832):     at android.app.ActivityThread.access$600(ActivityThread.java:128)
06-23 12:02:50.169: E/AndroidRuntime(5832):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1161)
06-23 12:02:50.169: E/AndroidRuntime(5832):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-23 12:02:50.169: E/AndroidRuntime(5832):     at android.os.Looper.loop(Looper.java:137)
06-23 12:02:50.169: E/AndroidRuntime(5832):     at android.app.ActivityThread.main(ActivityThread.java:4517)
06-23 12:02:50.169: E/AndroidRuntime(5832):     at java.lang.reflect.Method.invokeNative(Native Method)
06-23 12:02:50.169: E/AndroidRuntime(5832):     at java.lang.reflect.Method.invoke(Method.java:511)
06-23 12:02:50.169: E/AndroidRuntime(5832):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:993)
06-23 12:02:50.169: E/AndroidRuntime(5832):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:760)
06-23 12:02:50.169: E/AndroidRuntime(5832):     at dalvik.system.NativeStart.main(Native Method)
06-23 12:02:50.169: E/AndroidRuntime(5832): Caused by: android.os.NetworkOnMainThreadException
06-23 12:02:50.169: E/AndroidRuntime(5832):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
06-23 12:02:50.169: E/AndroidRuntime(5832):     at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
06-23 12:02:50.169: E/AndroidRuntime(5832):     at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
06-23 12:02:50.169: E/AndroidRuntime(5832):     at libcore.io.IoBridge.connect(IoBridge.java:112)
06-23 12:02:50.169: E/AndroidRuntime(5832):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
06-23 12:02:50.169: E/AndroidRuntime(5832):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
06-23 12:02:50.169: E/AndroidRuntime(5832):     at java.net.Socket.connect(Socket.java:848)
06-23 12:02:50.169: E/AndroidRuntime(5832):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:77)
06-23 12:02:50.169: E/AndroidRuntime(5832):     at libcore.net.http.HttpConnection. <init>(HttpConnection.java:50)
06-23 12:02:50.169: E/AndroidRuntime(5832):     at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:351)
06-23 12:02:50.169: E/AndroidRuntime(5832):     at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:86)
06-23 12:02:50.169: E/AndroidRuntime(5832):     at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
06-23 12:02:50.169: E/AndroidRuntime(5832):     at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:308)
06-23 12:02:50.169: E/AndroidRuntime(5832):     at libcore.net.http.HttpEngine.connect(HttpEngine.java:303)
06-23 12:02:50.169: E/AndroidRuntime(5832):     at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:282)
06-23 12:02:50.169: E/AndroidRuntime(5832):     at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:232)
 06-23 12:02:50.169: E/AndroidRuntime(5832):    at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80)
 06-23 12:02:50.169: E/AndroidRuntime(5832):    at libcore.net.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:188)
 06-23 12:02:50.169: E/AndroidRuntime(5832):    at com.e.testing.MainActivity.onCreate(MainActivity.java:80)
 06-23 12:02:50.169: E/AndroidRuntime(5832):    at android.app.Activity.performCreate(Activity.java:4470)
 06-23 12:02:50.169: E/AndroidRuntime(5832):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1053)
 06-23 12:02:50.169: E/AndroidRuntime(5832):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1934)
 06-23 12:02:50.169: E/AndroidRuntime(5832):    ... 11 more

在這個錯誤

 06-23 12:02:50.169: E/AndroidRuntime(5832):    at com.e.testing.MainActivity.onCreate(MainActivity.java:80)

MainActivity的第80行是

 dos = new DataOutputStream(conn.getOutputStream());
Caused by: android.os.NetworkOnMainThreadException

您正在嘗試在主線程上執行網絡任務,這是不允許的,請嘗試使用AsyncTask

您應該在AsyncTask或單獨的線程中運行此函數。

您的代碼試圖在主線程上執行網絡任務。 網絡任務將需要一些時間來請求和響應。 因此,您必須使用AysncTask。

http://developer.android.com/reference/android/os/AsyncTask.html

更新您的代碼:-(如下)

 class MyTask extends AsyncTask<Void, Void, Void> {

 protected RSSFeed doInBackground(String... urls) {
 HttpURLConnection conn = null;
        DataOutputStream dos = null;
        DataInputStream inStream = null;
        String existingFileName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Bluetooth/my.txt";
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        String responseFromServer = "";
        String urlString ="http://172.20.56.36:8084/AndroidTesting/UploadServlet.java";


        try {


            FileInputStream fileInputStream = new FileInputStream(new File(existingFileName));

            URL url = new URL(urlString);

            conn = (HttpURLConnection) url.openConnection();

            conn.setDoInput(true);

            conn.setDoOutput(true);

            conn.setUseCaches(false);

            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
         dos = new DataOutputStream(conn.getOutputStream());
            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + existingFileName + "\"" + lineEnd);
            dos.writeBytes(lineEnd);

            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];
            // read file and write it into form...
            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("Debug", "File is written");
            fileInputStream.close();
            dos.flush();
            dos.close();

        } catch(Exception e){
            Toast.makeText(getApplicationContext(),e.getMessage()+"error",Toast.LENGTH_SHORT).show();
        }




        //------------------ read the SERVER RESPONSE
        try {

            inStream = new DataInputStream(conn.getInputStream());
            String str;

             while ((str = inStream.readLine()) != null) {

                   Toast.makeText(getApplicationContext(),str,Toast.LENGTH_SHORT).show();
              }

            inStream.close();

        } catch (Exception ioex) {

          Toast.makeText(getApplicationContext(),ioex.getMessage()+"error",Toast.LENGTH_SHORT).show();
        }
     }

     protected void onPostExecute(Void feed) {

    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM