-1

I've been trying to post a multipart form in Android for the last couple of days but am not able to send string data and a file altogether. I'm using the following code to upload my file and it works just fine. But when it comes to adding String data to my request it falls short.

Imagine I need to append profile_id=1234&text=HERE IS MY TEXT&global=0 to the request. How can I do that?

String fileName = photoPath;

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;
try {

    // open a URL connection to the Servlet
    FileInputStream fileInputStream = new FileInputStream(new File(photoPath));
    URL url = new URL(Util.URL_POST_FEED);

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


    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)
    int serverResponseCode = conn.getResponseCode();
    String serverResponseMessage = conn.getResponseMessage();


    Log.i("uploadFile", "HTTP Response is : "
            + serverResponseMessage + ": " + serverResponseCode);

    if (serverResponseCode == 200) {

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


                Toast.makeText(c, "File Upload Complete.",
                        Toast.LENGTH_SHORT).show();
            }
        });
    }
    InputStream stream = conn.getInputStream();
    InputStreamReader isReader = new InputStreamReader(stream);

    //put output stream into a string
    BufferedReader br = new BufferedReader(isReader);
    Log.d("Read", br.readLine());
    //close the streams //
    fileInputStream.close();
    dos.flush();
    dos.close();

} catch (MalformedURLException ex) {

    ex.printStackTrace();

    runOnUiThread(new Runnable() {
        public void run() {
            Toast.makeText(c, "MalformedURLException",
                    Toast.LENGTH_SHORT).show();
        }
    });

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

    e.printStackTrace();

    runOnUiThread(new Runnable() {
        public void run() {
            Toast.makeText(c, "Got Exception : see logcat ",
                    Toast.LENGTH_SHORT).show();
        }
    });
    Log.e("Upload file to server Exception", "Exception : "
            + e.getMessage(), e);
}
2hamed
  • 8,719
  • 13
  • 69
  • 112
  • 1
    Check this http://www.codejava.net/java-se/networking/upload-files-by-sending-multipart-request-programmatically – Jaiprakash Soni Dec 15 '14 at 10:45
  • @JaiSoni Thanks, that worked perfectly. Do you mind putting it inside an answer so I can accept it? – 2hamed Dec 15 '14 at 11:48
  • Possible duplicate of [submit html form data using java to retrive a download from a jsp application](http://stackoverflow.com/questions/18153691/submit-html-form-data-using-java-to-retrive-a-download-from-a-jsp-application) – Mogsdad May 05 '16 at 14:37

1 Answers1

1

Check this tutorial. Hope it will be helpful.

It uses a custom MultipartUtility class which manually creates the request body to be sent over the connection.

2hamed
  • 8,719
  • 13
  • 69
  • 112
Jaiprakash Soni
  • 4,100
  • 5
  • 36
  • 67