java - 使用 HttpURLConnection 的 Android 分段文件上传 - 400 错误请求错误

标签 java android file-upload httpurlconnection multipartform-data

我正在尝试编写一个通用代码来将文件上传到任何服务器(Multipart POST)。
我在我的代码和各种stackoverflow解决方案中尝试了不同的 header 和请求类型,但仍然无法上传任何文件。

我不断收到以下 HTML 消息作为响应:
400 错误请求

<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>

如何编写通用代码将文件上传到 Android 中的服务器?

安卓代码:

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代码:

<?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!"; 
}

?> 

最佳答案

我成功地测试了我的代码。

看来问题出在免费托管网站上。 我现在创建了一个 servlet 并在我的机器上进行了本地测试,然后将其上传到 AWS 并通过设备进行了测试。这两种方式,我都能够从 Android 上传我的文件。

关于java - 使用 HttpURLConnection 的 Android 分段文件上传 - 400 错误请求错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40062974/

相关文章:

java - 如何创建动态 IF 语句?反射?

java - 如何在同一条语句中初始化队列

JavaFx:由于辅助打开窗口,我的主窗口如何要求确认关闭

android - logcat android studio 中的随机消息

java - 最新版本的 Android Studio 中 TextView 的文本对齐选项在哪里?

php - 使用 PHP 通过 ajax 上传文件时出现问题

HTML:如何将文件上传限制为仅图像?

java - Java 中基于正则表达式的字符串拆分

java - 我们如何动态地将数组从java文件添加到android中现有的xml文件中?

forms - 使用nodejs和connect-form上传文件