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;