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

我正在尝试编写通用代码以将文件上传到任何服务器(多部分POST).
我在代码和各种*解决方案中尝试了不同的标头和请求类型,但仍然无法上传任何文件.

我不断收到以下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中的服务器?

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上传文件.

上一篇:Request对象和Response对象详解


下一篇:Java-如何通过HttpUrlConnection发送表单数据或www-form-urlencoded数据