使用HttpURLConnection的Android多部分文件上传 - 400错误请求错误 [英] Android Multipart File Upload using HttpURLConnection - 400 Bad Request Error

查看:295
本文介绍了使用HttpURLConnection的Android多部分文件上传 - 400错误请求错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写一个通用的代码来上传文件到任何服务器(Multipart POST)。

我已经尝试了不同的头和请求类型在我的代码和各种各样的stackoverflow解决方案,但仍然无法上传任何文件。

以HTML消息作为响应:

400 BAD请求

 < html> ; 

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


函数toHex(){
for(var d = [],d = 1 == arguments.length&&&&& 0] .constructor == Array?arguments [0]:arguments,e =,f = 0; f 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>该网站需要使用Javascript才能正常运行,请在您的浏览器中启用Javascript,或使用带有Javascript支持的浏览器< / 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\\\
;
String twoHyphens = - ;
String boundary =*****;


int bytesRead,bytesAvailable,bufferSize;
byte [] buffer;
int maxBufferSize = 1 * 1024 * 1024;
文件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);
返回0;
} else {
try {
FileInputStream fileInputStream = new FileInputStream(selectedFile);
URL url =新的URL(serverURL);
conn =(HttpURLConnection)url.openConnection();
conn.setDoInput(true); //允许输入
conn.setDoOutput(true); //允许输出
conn.setUseCaches(false); //不要使用缓存副本
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);

//创建最大大小的缓冲区
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();

//服务器响应(代码和消息)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage()。toString();
$ b Log.i(TAG,HTTP Response is:+ serverResponseMessage +:+ serverResponseCode);

DataInputStream inStream;
String str =;
String response =;
尝试{
inStream = new DataInputStream(conn.getInputStream()); ((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();
//关闭流//
fileInputStream.close();
dos.flush();
dos.close();

if(serverResponseCode == 201){
Log.e(TAG,*** SERVER RESPONSE:201+ response);

$ b $ 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)){
echoThe file。 basename($ _FILES ['uploadedfile'] ['name'])。已上传;
} else {
echo上传文件时出现错误,请重试!;
}

?>


解决方案

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


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


I am trying to write a generic code to upload files to any server (Multipart POST).
I have tried different headers and request types in my code and various stackoverflow solutions, but still not able to upload any file.

I keep getting following HTML message as response:
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>

How can I write a generic code to upload files to servers in Android?

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 for testing file upload:

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

?> 

解决方案

I manage to test my code successfully.

It seems the issue was with the free hosting site. I now created a servlet and tested locally on my machine and I uploaded it to AWS and tested via the device. Both ways, I was able to upload my file from Android.

这篇关于使用HttpURLConnection的Android多部分文件上传 - 400错误请求错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆