Android使用多部分数据发布数据和文件

时间:2016-06-22 22:28:25

标签: android web-services post multipartform-data

我正在尝试使用多部分表单数据发送带有HTTP post的变量。我成功发送文件上传到服务器完美无瑕,但我无法在同一请求中发送变量。以下是我的示例代码。提前致谢

public int uploadFile(String sourceFileUri, String name, String description, String price, String category, String albumid, String artistid, String albumname) {


      String fileName = sourceFileUri;

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

      if (!sourceFile.isFile()) {

           dialog.dismiss(); 

           Log.e("uploadFile", "Source File not exist :"
                                + "" + uploadFileName);

           runOnUiThread(new Runnable() {
               public void run() {
                   messageText.setText("Source File not exist :"
                           + "" + uploadFileName);
               }
           }); 

           return 0;

      }
      else
      {
           try { 

                 // 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("uploaded_file", fileName); 
                conn.setRequestProperty("name", name); 
                conn.setRequestProperty("price", price); 
                conn.setRequestProperty("category", category); 
                conn.setRequestProperty("album", albumid); 
                conn.setRequestProperty("artist_id", artistid); 
                conn.setRequestProperty("album_name", albumname); 
               dos = new DataOutputStream(conn.getOutputStream());

               dos.writeBytes(twoHyphens + boundary + lineEnd); 
               dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_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);

               if(serverResponseCode == 200){

                   runOnUiThread(new Runnable() {
                        public void run() {

                            String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                          +uploadFileName;

                            messageText.setText(msg);
                            Toast.makeText(UploadToServer.this, "File Upload Complete."+JsonResponse, 
                                         Toast.LENGTH_SHORT).show();
                        }
                    });                
               }    

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

          } catch (MalformedURLException ex) {

              dialog.dismiss();  
              ex.printStackTrace();

              runOnUiThread(new Runnable() {
                  public void run() {
                      messageText.setText("MalformedURLException Exception : check script url.");
                      Toast.makeText(UploadToServer.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
                  }
              });

              Log.e("Upload file to server", "error: " + ex.getMessage(), ex);  
          } catch (Exception e) {

              dialog.dismiss();  
              e.printStackTrace();

              runOnUiThread(new Runnable() {
                  public void run() {
                      messageText.setText("Got Exception : see logcat ");
                      Toast.makeText(UploadToServer.this, "Got Exception : see logcat ", 
                              Toast.LENGTH_SHORT).show();
                  }
              });
              Log.e("Upload file to server Exception", "Exception : " 
                                               + e.getMessage(), e);  
          }
          dialog.dismiss();       
          return serverResponseCode; 

       } // End else block 
     } 

我在这里发送变量

conn.setRequestProperty("uploaded_file", fileName); 
            conn.setRequestProperty("name", name); 
            conn.setRequestProperty("price", price); 
            conn.setRequestProperty("category", category); 
            conn.setRequestProperty("album", albumid); 
            conn.setRequestProperty("artist_id", artistid); 
            conn.setRequestProperty("album_name", albumname); 
           dos = new DataOutputStream(conn.getOutputStream());

2 个答案:

答案 0 :(得分:1)

最后,经过大量的点击和试用,我的代码正常运行。发布它作为任何可能想在android中执行相同任务的人的答案

   public int uploadFile(String sourceFileUri, String name, String description, String price, String category, String albumid, String artistid, String albumname) {


      String fileName = sourceFileUri;

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

      if (!sourceFile.isFile()) {

           dialog.dismiss(); 

           Log.e("uploadFile", "Source File not exist :"
                                + "" + uploadFileName);

           runOnUiThread(new Runnable() {
               public void run() {
                   messageText.setText("Source File not exist :"
                           + "" + uploadFileName);
               }
           }); 

           return 0;

      }
      else
      {
           try { 

                 // 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("uploaded_file", fileName); 
                conn.setRequestProperty("name", name); 
                conn.setRequestProperty("price", price); 
                conn.setRequestProperty("category", category); 
                conn.setRequestProperty("desc", description); 
                    conn.setRequestProperty("album", albumid); 
                conn.setRequestProperty("artist_id", artistid); 
                conn.setRequestProperty("album_name", albumname); 
               dos = new DataOutputStream(conn.getOutputStream());

               dos.writeBytes(twoHyphens + boundary + lineEnd); 
               dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_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);

               if(serverResponseCode == 200){

                   runOnUiThread(new Runnable() {
                        public void run() {
                             BufferedReader br = null;
                            try {
                                br = new BufferedReader(new InputStreamReader(conn.getInputStream()));

                             StringBuilder sb = new StringBuilder();
                             String line;

                                while ((line = br.readLine()) != null) {
                                     sb.append(line+"\n");
                                 }
                                br.close();
                                 sb.toString();
                                String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                          +sb.toString();

                            messageText.setText(msg);

                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }

                              Toast.makeText(UploadToServer.this, "File Upload Complete."+JsonResponse, 
                                         Toast.LENGTH_SHORT).show();
                        }
                    });                
               }    

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

          } catch (MalformedURLException ex) {

              dialog.dismiss();  
              ex.printStackTrace();

              runOnUiThread(new Runnable() {
                  public void run() {
                      messageText.setText("MalformedURLException Exception : check script url.");
                      Toast.makeText(UploadToServer.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
                  }
              });

              Log.e("Upload file to server", "error: " + ex.getMessage(), ex);  
          } catch (Exception e) {

              dialog.dismiss();  
              e.printStackTrace();

              runOnUiThread(new Runnable() {
                  public void run() {
                      messageText.setText("Got Exception : see logcat ");
                      Toast.makeText(UploadToServer.this, "Got Exception : see logcat ", 
                              Toast.LENGTH_SHORT).show();
                  }
              });
              Log.e("Upload file to server Exception", "Exception : " 
                                               + e.getMessage(), e);  
          }
          dialog.dismiss();       
          return serverResponseCode; 

       } // End else block 
     } 

对于服务器端我正在使用php,所以我得到了$ SERVER中的所有键值,但要注意所有的ur键都将大写与HTML 自动连接,就像我发送的是album_name但是在服务器上$ _SERVER ['HTTP_ALBUM_NAME'];

$albumname=$_SERVER['HTTP_ALBUM_NAME'];

答案 1 :(得分:0)

我建议你使用okhttp。你可以这样使用它;

public void uploadFile(String sourceFileUri, String name, String description, String price, String category, String albumid, String artistid, String albumname, byte[] data) {
    MediaType MEDIA_TYPE_MP3 = MediaType.parse("audio/mpeg");
    OkHttpClient okHttpClient = new OkHttpClient();
    RequestBody requestBody = new MultipartBuilder()
            .type(MultipartBuilder.FORM)
            .addFormDataPart("uploaded_file", filename,
                    RequestBody.create(MEDIA_TYPE_MP3, data))
            .addFormDataPart("name", name)
            .addFormDataPart("price", price)
            .addFormDataPart("category", category)
            .addFormDataPart("album", album)
            .addFormDataPart("category", category)
            .addFormDataPart("artist_id", artistid)
            .addFormDataPart("album_name", albumname)
            .build();
    com.squareup.okhttp.Request request = new com.squareup.okhttp.Request.Builder()
            .url(upLoadServerUri)
            .post(requestBody)
            .build();
    okHttpClient.newCall(request).enqueue(new com.squareup.okhttp.Callback() {

        @Override
        public void onFailure(com.squareup.okhttp.Request request, IOException e) {

        }

        @Override
        public void onResponse(final com.squareup.okhttp.Response response) throws IOException {

        }
    });
}