Question

I need to send a file from an Android application (200 - 500 kb). I have tried selected scripts, but these have returned errors.

private void doFileUpload(String filename) {
    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    DataInputStream inStream = null;
    String existingFileName = filename;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary =  "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1*1024*1024;
    String responseFromServer = "";
    String urlString = "http://scary-story.ru/";

    try {
        //------------------ CLIENT REQUEST
        FileInputStream fileInputStream = new FileInputStream(new File(existingFileName) );
        // open a URL connection to the Servlet
        URL url = new URL(urlString);
        // Open a HTTP connection to the URL
        conn = (HttpURLConnection) url.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);
        dos = new DataOutputStream( conn.getOutputStream() );
        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + existingFileName + "\"" + lineEnd);
        dos.writeBytes(lineEnd);
        // create a buffer of maximum size
        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 (MalformedURLException ex) {
        Log.e("Debug", "error: " + ex.getMessage(), ex);
    }
    catch (IOException ioe) {
        Log.e("Debug", "error: " + ioe.getMessage(), ioe);
    }


    //------------------ read the SERVER RESPONSE
    try {
        inStream = new DataInputStream(conn.getInputStream());
        String str;

        while ((str = inStream.readLine()) != null) {
            Log.e("Debug","Server Response "+str);
        }
        inStream.close();
    }
    catch (IOException ioex) {
         Log.e("Debug", "error: " + ioex.getMessage(), ioex);
    }
}

This script return next error and app force close.

01-28 16:54:20.729: E/AndroidRuntime(5647): FATAL EXCEPTION: main
01-28 16:54:20.729: E/AndroidRuntime(5647): android.os.NetworkOnMainThreadException
01-28 16:54:20.729: E/AndroidRuntime(5647):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1100)
01-28 16:54:20.729: E/AndroidRuntime(5647):     at java.net.InetAddress.lookupHostByName(InetAddress.java:426)
01-28 16:54:20.729: E/AndroidRuntime(5647):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:277)
01-28 16:54:20.729: E/AndroidRuntime(5647):     at java.net.InetAddress.getAllByName(InetAddress.java:251)
01-28 16:54:20.729: E/AndroidRuntime(5647):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:71)
01-28 16:54:20.729: E/AndroidRuntime(5647):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
01-28 16:54:20.729: E/AndroidRuntime(5647):     at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:351)
01-28 16:54:20.729: E/AndroidRuntime(5647):     at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:86)
01-28 16:54:20.729: E/AndroidRuntime(5647):     at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
01-28 16:54:20.729: E/AndroidRuntime(5647):     at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:308)
01-28 16:54:20.729: E/AndroidRuntime(5647):     at libcore.net.http.HttpEngine.connect(HttpEngine.java:303)
01-28 16:54:20.729: E/AndroidRuntime(5647):     at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:282)
01-28 16:54:20.729: E/AndroidRuntime(5647):     at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:232)
01-28 16:54:20.729: E/AndroidRuntime(5647):     at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80)
01-28 16:54:20.729: E/AndroidRuntime(5647):     at libcore.net.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:188)
01-28 16:54:20.729: E/AndroidRuntime(5647):     at com.example.testapp1.MainActivity.doFileUpload(MainActivity.java:342)
01-28 16:54:20.729: E/AndroidRuntime(5647):     at com.example.testapp1.MainActivity.stopRecording(MainActivity.java:186)
01-28 16:54:20.729: E/AndroidRuntime(5647):     at com.example.testapp1.MainActivity.access$2(MainActivity.java:170)
01-28 16:54:20.729: E/AndroidRuntime(5647):     at com.example.testapp1.MainActivity$1.onClick(MainActivity.java:302)
01-28 16:54:20.729: E/AndroidRuntime(5647):     at android.view.View.performClick(View.java:3524)
01-28 16:54:20.729: E/AndroidRuntime(5647):     at android.view.View$PerformClick.run(View.java:14226)
01-28 16:54:20.729: E/AndroidRuntime(5647):     at android.os.Handler.handleCallback(Handler.java:605)
01-28 16:54:20.729: E/AndroidRuntime(5647):     at android.os.Handler.dispatchMessage(Handler.java:92)
01-28 16:54:20.729: E/AndroidRuntime(5647):     at android.os.Looper.loop(Looper.java:137)
01-28 16:54:20.729: E/AndroidRuntime(5647):     at android.app.ActivityThread.main(ActivityThread.java:4516)
01-28 16:54:20.729: E/AndroidRuntime(5647):     at java.lang.reflect.Method.invokeNative(Native Method)
01-28 16:54:20.729: E/AndroidRuntime(5647):     at java.lang.reflect.Method.invoke(Method.java:511)
01-28 16:54:20.729: E/AndroidRuntime(5647):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-28 16:54:20.729: E/AndroidRuntime(5647):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-28 16:54:20.729: E/AndroidRuntime(5647):     at dalvik.system.NativeStart.main(Native Method)

Excuse my English, I'm Ukrainian student.

PS: Sending images using Http Post - this method not work

Was it helpful?

Solution

NetworkOnMainThreadException is occured when you do Network related operations on Main Thread. Refer this link to solve your issue.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top