0

And Python there's a pretty standard code for sending a multipart-form data, or rather, encoding it:

def encode_multipart_formdata(fields, files):
  # fields is a sequence of (name, value) elements for regular form fields.
  # files is a sequence of (name, filename, value) elements for data to be uploaded as files
  # Return (content_type, body) ready for httplib.HTTP instance
  BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$'
  CRLF = '\r\n'
  L = []
  for (key, value) in fields:
    L.append('--' + BOUNDARY)
    L.append('Content-Disposition: form-data; name="%s"' % key)
    L.append('')
    L.append(value)
  for (key, filename, value) in files:
    L.append('--' + BOUNDARY)
    L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
    L.append('Content-Type: %s' % get_content_type(filename))
    L.append('')
    L.append(value)
  L.append('--' + BOUNDARY + '--')
  L.append('')
  body = CRLF.join(L)
  content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
  return content_type, body

I wonder, how can I do the same thing, encode multipart formdata, in Android?

I found a few solutions but none of them were supposed to do exactly the same thing as this one in python.

Jenny T.
  • 13
  • 5
  • Try this: http://stackoverflow.com/questions/2017414/post-multipart-request-with-android-sdk – linus Oct 27 '15 at 09:56
  • @linus, that seems very complicated for such a simple task -- I'll have to download an additional library. – Jenny T. Oct 27 '15 at 10:14

1 Answers1

1

I checked if i used this code before, i can't really remember how exactly this works but here:

    HttpURLConnection conn = null;
    DataOutputStream dOut = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";

      URL url = new URL("http://shrimptalusan.hostei.com/usbong/build-upload.php");

      conn = (HttpURLConnection) url.openConnection();
      conn.setDoInput(true);
      conn.setDoOutput(true);
      conn.setUseCaches(false);

setup the start of the multipart form:

      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("utreeFile", utreeFilePath);

      dOut = new DataOutputStream(conn.getOutputStream());
      dOut.writeBytes(twoHyphens + boundary + lineEnd);
      dOut.writeBytes("Content-Disposition: form-data; name=\"utreeFile\";filename=\"" + utreeFilePath + "\"" + lineEnd);
      dOut.writeBytes(lineEnd);

      bytesAvailable = utreeFileIn.available();
      bufferSize = Math.min(bytesAvailable, maxBuffersize);
      buffer = new byte[bufferSize];
      bytesRead = utreeFileIn.read(buffer, 0, bufferSize);

Reading the file into a buffer:

      while (bytesRead > 0) {
          progress += bytesRead;
          dOut.write(buffer, 0, bufferSize);
          bytesAvailable = utreeFileIn.available();
          publishProgress((int) ((progress * 100) / (utreeFile.length())));
          bufferSize = Math.min(bytesAvailable, maxBuffersize);
          buffer = new byte[bufferSize]; //TEST
          bytesRead = utreeFileIn.read(buffer, 0, bufferSize);
      }

Additional parameters to be included in the multipart entity:

      //PARAMETER FIELD NAME
      dOut.writeBytes(twoHyphens + boundary + lineEnd);
      dOut.writeBytes("Content-Disposition: form-data; name=\"youtubelink\"" + lineEnd);
      dOut.writeBytes(lineEnd);
      dOut.writeBytes(youtubeLink); // mobile_no is String variable
      dOut.writeBytes(lineEnd);
      //PARAMETER END

Ending the multipart:

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

Sending the multipart via HTTP:

      if (conn.getResponseCode() != HttpsURLConnection.HTTP_OK) {
          utreeFileIn.close();
          throw new RuntimeException("Failed : HTTP error code : "
                  + conn.getResponseCode());
      } else {
          BufferedReader br = new BufferedReader(new InputStreamReader(
                  (conn.getInputStream())));
          String line;
          while ((line = br.readLine()) != null) {
              System.out.println(line);
              responseString += line;
          }
      }

Closing files and connections:

    utreeFileIn.close();
    dOut.flush();
    dOut.close();

Hopefully it gives you a better idea. I don't think i used any external libraries. Here are my imports:

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
linus
  • 481
  • 5
  • 18