Java HttpURLConnection和使用数据写入文件

Java HttpURLConnection和使用数据写入文件,java,php,android,httpurlconnection,Java,Php,Android,Httpurlconnection,我正试图将一个文件和数据从Android java脚本(到我的php)发布到我的服务器上,看起来我差不多在那里,但有人请帮助我,因为我似乎无法格式化名称/值部分(文件上传完美,但不发送名称值:() 爪哇: 它不起作用,文件发送很好,但我无法获得要发送的异常密钥/名称(“gmail:“名称[0]),我也尝试过: // Open a HTTP connection to the URL conn = (HttpURLConnection)

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

爪哇:

它不起作用,文件发送很好,但我无法获得要发送的异常密钥/名称(“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("Content-Disposition: form-data; name=\"gmail\";filename=\""+ names[0] + "\"" + lineEnd);

不工作!WTF!我已经用C++和Python编程了很多年,这是一件简单的事情!但是我不能理解我需要帮助,如果你知道怎么做,请告诉我,因为我花了两天的时间把头撞在墙上。我不懒,我花了32个小时,我恳求你…… 我希望发生的事情:发送文件进行上传,同时发送值(name=gmail value=names[0];name=phn value=phn),以便将电子邮件与我服务器上的文件关联。 发生的情况:文件上传正常,但未传递数据(未发送名称/值对)

PHP:


您应该认真阅读以下内容:HTTP(以及请求头字段和post正文之间的区别),以及多部分/表单数据post正文的结构

这:

发送一些请求标题,这对于
内容类型
等很好,但不一定适用于您发布的数据。除了
内容类型
行之外,丢失所有内容

这:

如果是启动post字段(或文件)的正确方法,则应该为每个post字段输出此选项

这:

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


使用Wireshark之类的工具查看最终请求的外观(任何一方都会这样做;执行请求的设备或处理请求的服务器),或记录您的请求,以便检查它是否完美。Web服务器/php必须近乎完美才能正确处理它。

好吧,我从来没有想过如何在文件上载时发送简单的字符串参数,但我的解决方法是简单地附加上载文件的文件名,以包含我想要发送的字符串:

 @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){


    }

}
@SuppressWarnings(“弃用”)
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
试一试{
Account[]accounts=AccountManager.get(this.getAccountsByType(“com.google”);
字符串myEmailid=accounts[0].toString();Log.d(“我想要的电子邮件id”,myEmailid);
字符串[]名称=新字符串[accounts.length];
for(int i=0;i0){
写入(缓冲区,0,缓冲区大小);
bytesAvailable=fileInputStream.available();
bufferSize=Math.min(字节可用,maxBufferSize);
bytesRead=fileInputStream.read(bu
dos.writeBytes("Content-Disposition: form-data; name=\"gmail\";filename=\""+ names[0] + "\"" + lineEnd);
    <?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);


?>
         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.writeBytes(twoHyphens + boundary + lineEnd); 
         dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
 @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){


    }

}