java - HttpURLConnection 和用数据写入文件

标签 java php android httpurlconnection

我正在尝试从 Android java 脚本(到我的 php)将文件和数据发布到我的服务器,看来我已经差不多了,但是请有人帮助我,因为我似乎无法格式化名称/值部分(文件上传完美,但它不发送名称值 :( )

Java:

                try{
         int serverResponseCode = 0;
            final String upLoadServerUri = "http://myUrl/upload_file_functions.php";
          String fileName = "/mnt/sdcard/myFile.dat";

            HttpURLConnection conn = null;
            DataOutputStream dos = null;  
            String lineEnd = "\r\n";
            String twoHyphens = "--";
            String boundary = "*****";
            int bytesRead, bytesAvailable, bufferSize;
            byte[] buffer;
            int maxBufferSize = 1 * 1024 * 1024; 
            File sourceFile = new File("/mnt/sdcard/myFile.dat"); 


                     // open a URL connection to the Servlet
                       FileInputStream fileInputStream = new FileInputStream(sourceFile);
                       URL url = new URL(upLoadServerUri);

                       // Open a HTTP  connection to  the URL
                       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("file", fileName); 
                       conn.setRequestProperty("gmail", names[0]);
                       conn.setRequestProperty("phn", phn);

                       dos = new DataOutputStream(conn.getOutputStream());

                       dos.writeBytes(twoHyphens + boundary + lineEnd); 
                       dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\""
                                                 + fileName + "\"" + lineEnd);

                       dos.writeBytes(twoHyphens + boundary + lineEnd);


                       String data = URLEncoder.encode("gmail", "UTF-8") + "=" + URLEncoder.encode(names[0], "UTF-8");
                       dos.writeBytes(data);



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





                       dos.writeBytes("Content-Disposition: form-data; name=\"" + names[0] + "\"" + lineEnd);
                       dos.writeBytes("Content-Type: text/plain"+lineEnd);
                       dos.writeBytes(lineEnd);
                       dos.writeBytes(names[0]);
                       dos.writeBytes(lineEnd);

                       dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);


                       //*************************



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

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

                       if(serverResponseCode == 200){

                           // it worked !
                       }    




                       //close the streams //
                       fileInputStream.close();
                       dos.flush();
                       dos.close();

        }catch (Exception e){

        }

它不起作用,FILE 发送正常,但我无法获得要发送的该死的 key /名称(“gmail:”names[0])我也试过:

 // Open a HTTP  connection to  the URL
                           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("Content-Type", "multipart/form-data;boundary=" + boundary);

                           conn.setRequestProperty("gmail", names[0]);

dos.writeBytes(twoHyphens + boundary + lineEnd);

                           dos = new DataOutputStream(conn.getOutputStream());

                           dos.writeBytes(twoHyphens + boundary + lineEnd); 
                           dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\""
                                                     + fileName + "\"" + lineEnd);

                           dos.writeBytes(twoHyphens + boundary + lineEnd);

不起作用。我试过:

dos.writeBytes("Content-Disposition: form-data; name=\"gmail\";filename=\""+ names[0] + "\"" + lineEnd);

没用!卧槽!我用 C++ 和 Python 编程多年,这很简单!但我想不通,我需要帮助,如果你知道怎么做,请告诉我,因为我花了两天时间用头撞墙。我并不懒惰,我在这上面花了 32 多个小时,求求你了..

我想要发生的事情:发送要上传的文件以及值(名称=gmail 值=名称[0];名称=phn 值=phn),以便电子邮件与我服务器上的文件相关联. 发生了什么:文件上传正常,但数据未传递(未发送名称/值对)

PHP:

    <?php

    set_time_limit(100);


    //need to get email also (gmail address of user)

    //************************************************
    if ($_FILES["file"]["error"] > 0)
      {
      echo "Error: " . $_FILES["file"]["error"] . "<br>";
      }
    else
      {
      echo "Upload: " . $_FILES["file"]["name"] . "<br>";
      echo "Type: " . $_FILES["file"]["type"] . "<br>";
      echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
      echo "Stored in: " . $_FILES["file"]["tmp_name"];
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      }
    }



    function Three(){

    $to =    'me@email.com';
    $subject =   $_POST['phn'] . " " . $_POST['gmail'];
    $bound_text =   "file";
$bound =    "--".$bound_text."\r\n";
$bound_last =   "--".$bound_text."--\r\n";

$headers =  "From: me@email.com\r\n";
$headers .= "MIME-Version: 1.0\r\n"
    ."Content-Type: multipart/mixed; boundary=\"$bound_text\"";

$message .= "If you can see this MIME than your client doesn't accept MIME types!\r\n"
    .$bound;

$message .= "Content-Type: text/html; charset=\"iso-8859-1\"\r\n"
    ."Content-Transfer-Encoding: 7bit\r\n\r\n"
    ."hey my <b>good</b> friend here is a picture of regal beagle\r\n"
    .$bound;

$file = file_get_contents("http://myURL/upload/myFile.dat");

$message .= "Content-Type: image/jpg; name=\"myFile.dat\"\r\n"
    ."Content-Transfer-Encoding: base64\r\n"
    ."Content-disposition: attachment; file=\"myFile.dat"\r\n"
    ."\r\n"
    .chunk_split(base64_encode($file))
    .$bound_last;
@mail($to, $subject, $message, $headers);

//delete files
$fileArray=array($_FILES["file"]["name"],"myfile.dat","myfile.dat");
foreach($fileArray as $value){
 if(file_exists($value)){
  unlink($value);
 }
}

chdir($old_path);
}

function runAll(){
 One();
 Two();
 Three();
}
runAll();
$randx=null;
unset($randx);


?>

请帮忙! JAVA 不发送 name='gmail' value=names[0],也不发送 name='phn' value=phn ..

最佳答案

您真的应该仔细阅读一些内容:HTTP(以及请求 header 字段和帖子正文之间的区别),以及多部分/表单数据帖子正文的结构。

这个:

         conn.setRequestProperty("Connection", "Keep-Alive");
         conn.setRequestProperty("ENCTYPE", "multipart/form-data");
         conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
         conn.setRequestProperty("file", fileName); 
         conn.setRequestProperty("gmail", names[0]);
         conn.setRequestProperty("phn", phn);

发送一些请求 header ,这适用于Content-Type 等,但不一定适用于您发布的数据。丢失除 Content-Type 行之外的所有内容。

这个:

         dos.writeBytes(twoHyphens + boundary + lineEnd); 

是开始发布字段(或文件)的正确方法,您应该为每个发布的字段输出它。

这个:

         dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

所有字段都已发送的信号,您应该将其作为最后一行发送。

要么使用 Wireshark 之类的东西来查看您的最终请求是什么样的(任何一方都可以;执行请求的设备或处理它的服务器),或者记录您的请求以便您检查它,看看它是否完美.它必须近乎完美,网络服务器/php 才能正确处理它。

关于java - HttpURLConnection 和用数据写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23188300/

相关文章:

java - 使用 Spring Boot 启动 Web 服务时出错

java - DynamoDB DynamoDBAutoGenerateStrategy.CREATE 不适用于 DynamoDBMapperConfig.SaveBehavior.UPDATE_SKIP_NULL_ATTRIBUTES

javascript - 自动增加客户数量。

Android Studio 继续获得 Unsupported major.minor 版本 52.0

javascript - webview 加载网页,但一些内容在加载后消失(Android Studio)

java - object.super() 的作用是什么?如何创建国家?

java - Scala(和Java)中的类和类型有什么区别?

php - Codeigniter MySQL 连接查询

php - 内容();在我的 wordpress 自定义模板页面中不打印任何内容

android - checkbox.setClickable(false) 在 android 中不起作用