I use the following method to send a file to a server, I receive it with PHP in the variable $ _FILE, the truth is that I do not understand this method 100% and I do not know if I can add more data, I would like to send it together to file a couple of texts like those that are usually sent by post and receive with the variable $ _POST, is there a way to modify this code and achieve it?
public String postArchivo(String pathToOurFile) {
HttpURLConnection conn = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte [] buffer;
int maxBufferSize = 1 * 1024 * 1024;
try {
FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile));
URL url = new URL(context.getResources().getString(R.string.url_base) + "audio");
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
outputStream = new DataOutputStream(conn.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
+ pathToOurFile + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while(bytesRead > 0) {
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
/*int serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
return serverResponseMessage;*/
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
String respost = "";
while((line = in.readLine()) != null) {
respost += line;
}
return respost;
}
catch(Exception e) {
return "Error: " + e;
}
finally {
if(conn != null)
conn.disconnect();
}
}