Android Multipart File Upload mit HttpURLConnection - 400 Bad Request Error

Ich versuche, einen generischen Code zu schreiben, um Dateien auf einen beliebigen Server hochzuladen (Multipart POST).
Ich habe verschiedene Header und Anfragetypen in meinem Code und in verschiedenen Stackoverflow-Lösungen ausprobiert, kann aber immer noch keine Datei hochladen.

Ich erhalte folgende HTML-Nachricht als Antwort:
400 BAD Request

<html>

<body>
    <script type="text/javascript" src="/aes.js"></script>
    <script>
        function toNumbers(d) {
            var e = [];
            d.replace(/(..)/g, function(d) {
                e.push(parseInt(d, 16))
            });
            return e
        }

        function toHex() {
            for (var d = [], d = 1 == arguments.length && arguments[0].constructor == Array ? arguments[0] : arguments, e = "", f = 0; f < d.length; f++) e += (16 > d[f] ? "0" : "") + d[f].toString(16);
            return e.toLowerCase()
        }
        var a = toNumbers("f655ba9d09a112d4968c63579db590b4"),
            b = toNumbers("98344c2eee86c3994890592585b49f80"),
            c = toNumbers("0a569f28135dfc293e0b189974d6ae3d");
        document.cookie = "__test=" + toHex(slowAES.decrypt(c, 2, a, b)) + "; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/";
        location.href = "http://xxxxxxxxxx/uploadServer.php?i=1";
    </script>
    <noscript>This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support</noscript>
</body>

</html>

Wie kann ich einen generischen Code schreiben, um Dateien auf Server in Android hochzuladen?

Android Code:

private int uploadFile(final String selectedFilePath, String serverURL) {
        Log.d(TAG, "uploadFile.... File->"+selectedFilePath+"   to   Server->"+serverURL);
        int serverResponseCode = 0;

        HttpURLConnection conn;
        DataOutputStream dos;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";


        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        File selectedFile = new File(selectedFilePath);


        String[] parts = selectedFilePath.split("/");
        final String fileName = parts[parts.length - 1];
        Log.d(TAG, fileName);
        if (!selectedFile.isFile()) {
            // TODO no file exists
            Log.i(TAG, selectedFile+" not exists");
            return 0;
        } else {
            try {
                FileInputStream fileInputStream = new FileInputStream(selectedFile);
                URL url = new URL(serverURL);
                conn = (HttpURLConnection) url.openConnection();
                conn.setDoInput(true); // Allow Inputs
                conn.setDoOutput(true); // Allow Outputs
                conn.setUseCaches(false); // Don't use a Cached Copy            
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                conn.setRequestProperty("uploadedfile", fileName);
                conn.setRequestProperty("connection", "close");
                dos = new DataOutputStream(conn.getOutputStream());
                dos.writeBytes(twoHyphens + boundary + lineEnd);
                dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + fileName + "\"" + lineEnd);
                dos.writeBytes(lineEnd);

                // create a buffer of  maximum size
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];
                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);
                    Log.i(TAG,"while..");
                }
                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
                conn.connect();

                // Responses from the server (code and message)
                serverResponseCode = conn.getResponseCode();
                String serverResponseMessage = conn.getResponseMessage().toString();

                Log.i(TAG, "HTTP Response is : "  + serverResponseMessage + ": " + serverResponseCode);

                DataInputStream inStream;
                String str="";
                String response="";
                try {
                    inStream = new DataInputStream(conn.getInputStream());

                    while ((str = inStream.readLine()) != null) {
                        Log.e(TAG, "SOF Server Response" + str);
                        response=str;
                    }
                    inStream.close();
                }
                catch (IOException ioex) {
                    Log.e(TAG, "SOF error: " + ioex.getMessage(), ioex);
                }
                conn.disconnect();
                //close the streams //
                fileInputStream.close();
                dos.flush();
                dos.close();

                if(serverResponseCode == 201){
                    Log.e(TAG,"*** SERVER RESPONSE: 201"+response);
                }
            }
            catch (MalformedURLException ex) {
                ex.printStackTrace();
                Log.e(TAG, "UL error: " + ex.getMessage(), ex);
            } 

            catch (Exception e) {
                e.printStackTrace();
                Log.e(TAG, "Exception : "+ e.getMessage());
            }

            return serverResponseCode; 
        }


PHP-Code zum Testen des Datei-Uploads:

<?php 

$target_path = "uploads/"; 

$target_path = $target_path . basename( $_FILES['uploadedfile']['name']); 

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) { 
    echo "The file ". basename( $_FILES['uploadedfile']['name'])." has been uploaded"; 
} else{ 
    echo "There was an error uploading the file, please try again!"; 
}

?> 

Antworten auf die Frage(2)

Ihre Antwort auf die Frage