2017-10-04 32 views
0

我有上傳文件的代碼通過http:的Android通過HttpURLConnection的發送HTTP文件參數和非文件

FileInputStream fileInputStream = new FileInputStream(selectedFile); 
      URL url = new URL(SERVER_URL); 
      connection = (HttpURLConnection) url.openConnection(); 
      connection.setDoInput(true);//Allow Inputs 
      connection.setDoOutput(true);//Allow Outputs 
      connection.setUseCaches(false);//Don't use a cached Copy 
      connection.setRequestMethod("POST"); 
      connection.setRequestProperty("Connection", "Keep-Alive"); 
      connection.setRequestProperty("ENCTYPE", "multipart/form-data"); 
      connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); 
      connection.setRequestProperty("uploaded_file",selectedFilePath); 



      //creating new dataoutputstream 
      dataOutputStream = new DataOutputStream(connection.getOutputStream()); 

      //writing bytes to data outputstream 
      dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd); 
      dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" 
        + selectedFilePath + "\"" + lineEnd); 

      dataOutputStream.writeBytes(lineEnd); 

,但我需要發送用戶信息太像郵件/密碼

我想這樣但只有文件上傳和用戶信息轉爲空:

FileInputStream fileInputStream = new FileInputStream(selectedFile); 
      URL url = new URL(SERVER_URL); 
      connection = (HttpURLConnection) url.openConnection(); 
      connection.setDoInput(true);//Allow Inputs 
      connection.setDoOutput(true);//Allow Outputs 
      connection.setUseCaches(false);//Don't use a cached Copy 
      connection.setRequestMethod("POST"); 
      connection.setRequestProperty("Connection", "Keep-Alive"); 
      connection.setRequestProperty("ENCTYPE", "multipart/form-data"); 
      connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); 
      connection.setRequestProperty("uploaded_file",selectedFilePath); 
      connection.setRequestProperty("user",user); 

我加入connection.setRequestProperty(「用戶」,用戶);但在服務器端它來空

$user = $_POST['user']; 

我怎麼可以在同一httpurlconnection發送文件和用戶信息?

回答

0

我解決把這個代碼:

dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd); 
      dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"myparameter\"" + lineEnd); 
      dataOutputStream.writeBytes(lineEnd); 
      dataOutputStream.writeBytes(myvalue); 

其中myparameter是參數和myvalue的是參數的值