将文本文件从android上传到服务器,获取错误

时间:2014-06-23 04:46:45

标签: android

这是我在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块,然后我得到一个null错误,我认为它在这一行

              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());

3 个答案:

答案 0 :(得分:1)

Caused by: android.os.NetworkOnMainThreadException

您正尝试在主线程上执行网络任务,这是不允许的,请尝试使用AsyncTask

答案 1 :(得分:0)

您应该在AsyncTask或单独的线程中运行此函数。

答案 2 :(得分:0)

您的代码尝试在主线程上执行网络任务。网络任务需要一些时间来请求和响应。所以你必须使用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) {

    }
}