HttpURLConnection和写入文件WITH DATA

时间:2014-04-20 22:27:36

标签: java php android httpurlconnection

我试图通过Android java脚本(到我的php)将文件和数据发布到我的服务器上,似乎我已经在那里,但有人请帮助我,因为我可以&# 39;似乎格式化名称/值部分(FILE上传完美,但它没有发送名称值:()

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发送正常,但我无法获得一个怪异的密钥/名称发送(" gmail:"名称[0])我&#39 ; ve也尝试过:

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

DOESN'工作。我试过了:

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

不工作! WTF!我已经用C ++和python编程多年了,这很简单!但我无法弄清楚我需要帮助,如果你知道该怎么做请请告诉我,因为我花了两天时间撞到了墙上。我不懒,我花了32多个小时,请求你...

我想要发生的事情:发送要上传的文件以及值(name = gmail value = names [0]; name = phn value = 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没有发送名称=&#39; gmail&#39; value = names [0],名称=&#39; phn&#39; value = phn ..

2 个答案:

答案 0 :(得分:1)

您应该阅读以下几点:HTTP(以及请求标题字段和帖子正文之间的区别),以及multipart / form-data帖子正文的结构。

此:

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

发送一些请求标头,这对于Content-Type这样很好,但不一定适用于您发布的数据。丢失Content-Type行以外的所有内容。

此:

         dos.writeBytes(twoHyphens + boundary + lineEnd); 

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

此:

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

表示已发送所有字段,您应该将其作为最后一行发送。

使用像Wireshark这样的东西来查看你的最终请求是什么样的(任何一方都会这样做;执行请求的设备或处理它的服务器),或者记录你的请求以便你可以检查它,看看它是否完美。它必须几乎完美的webserver / php才能正确处理它。

答案 1 :(得分:1)

好吧,我从未弄清楚如何使用文件上传发送简单的字符串参数,但我的解决方法是简单地将上传文件的文件名附加到INCLUDE我要发送的字符串:

 @SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {       
    super.onCreate(savedInstanceState);        
    addPreferencesFromResource(R.xml.preferences); 




    try{

            Account[] accounts=AccountManager.get(this).getAccountsByType("com.google");
            String myEmailid=accounts[0].toString(); Log.d("My email id that i want", myEmailid);

            String[] names = new String[accounts.length];
            for (int i = 0; i < names.length; i++) {
                names[i] = accounts[i].name;
            }
            // THE DEVICE EMAIL ADDRESS WAS ONE OF THE DATA STRINGS I NEEDED TO SEND


            File from = new File("/mnt/sdcard/","UPLOADFILE.DAT");
            File to = new File("/mnt/sdcard/",names[0]+".BLOCK1."+"DATASTRING2"+".BLOCK2");
            from.renameTo(to);

            // DATASTRING2 is the SECOND piece of DATA I wanted to send
            // SO YOU SEE I'M SIMPLY APPENDING THE UPLOAD FILE WITH THE DATA I WANT
            // TO SEND WITH THE FILE, AND WHEN MY SERVER RECEIVES IT, I USE SOME SIMPLE
            // PHP TO PARSE OUT WHATS BEFORE .BLOCK1. AND THEN .BLOCK2

         StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
         StrictMode.setThreadPolicy(policy); 

        try{
         int serverResponseCode = 0;
            final String upLoadServerUri = "http://MYURL/upload_file_functions.php";
          String fileName = "/mnt/sdcard/"+names[0]+".BLOCK1."+"DATASTRING2"+".BLOCK2";

            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/"+names[0]+".BLOCK1."+"DATASTRING2"+".BLOCK2""); 


                     // 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("Content-Type", "multipart/form-data;boundary=" + boundary);
                       dos = new DataOutputStream(conn.getOutputStream());
                       dos.writeBytes(twoHyphens + boundary + lineEnd); 
                       dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\""+ fileName + "\"" + lineEnd);
                       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);


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

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

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

        }catch (Exception e){

        }


    }catch (Exception e){


    }

}

感谢您的帮助! (严格的SARCASM ..)说真的,我必须在python,C ++,java,PHP,Linux,Android,iPhone,Windows,MAC和Ubuntu上编码......我的工作让我构建了Triple-Boot OS box&#39; s,在Android和iPhone中构建应用程序以支持我的业务需求,因此我必须知道配置我自己的服务器所需的PHP html等,因为我需要电子邮件通知服务,所以我需要运行自己的电子邮件服务器(Exim在Ubuntu服务器上),我在过去的6个月里不得不学习这一切。

请原谅我,如果我的代码不漂亮,但我没有时间的奢侈,因为我要去INSANE试图跟上人工智能,对象识别和试图赚取租金(尽管我已经学会了这么做......) DC:)