簡體   English   中英

HttpURLConnection和寫入文件WITH DATA

[英]HttpURLConnection and writing file WITH DATA

我正試圖從Android java腳本(到我的php)將文件和數據發布到我的服務器,看來我差不多了,但有人請幫助我,因為我似乎無法格式化名稱/值部分(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])我也嘗試過:

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

不工作! 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沒有發送name ='gmail'value = names [0],也沒有發送name ='phn'value = phn ..

您應該閱讀以下幾點: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正確處理它。

好吧,我從來沒有弄清楚如何使用文件上傳發送一個簡單的字符串參數,但我的解決方法是簡單地將上傳文件的文件名附加到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盒子,構建應用程序在Android和iPhone中支持我的業務需求,因此我必須知道PHP html之類的,需要配置我自己的服務器,因為我需要電子郵件通知服務,所以我需要運行自己的電子郵件服務器(Exim在Ubuntu服務器上) ,在過去的6個月里,我必須學習這一切。

原諒我,如果我的代碼不漂亮,但我沒有時間的奢侈,因為我要INSANE試圖跟上人工智能,物體識別,並試圖賺取租金(雖然我已經學會了足以這樣做..)DC :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM