I am trying to make a POST request using "multipart/form-data" , i need to post a file (Code Below) and 4 parameters(Name,category ...) all Strings.
I can already send the File using code below but never with parameters.
// 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("fileToUpload", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"fileToUpload\";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() {
Toast.makeText(PerdidosEAchados.this, "File Upload Complete.",
Toast.LENGTH_SHORT).show();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
The server Code
<?php
echo $_POST["Name"]) ;
echo $_POST["category "]) ;
?>
I have tryed adding
dos.writeBytes("Content-Disposition: form-data; name=\"Name\";" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(Variable);
But the server never registers the parameters, how can i solve this?
Maybe you shuold build the POST request like the forrowing demo code? Hope it helps.
### Send a form with the text and file fields
POST https://httpbin.org/post
Content-Type: multipart/form-data; boundary=WebAppBoundary
--WebAppBoundary
Content-Disposition: form-data; name="Name"
myName
--WebAppBoundary
Content-Disposition: form-data; name="category"
myCategory
--WebAppBoundary
Content-Disposition: form-data; name="data"; filename=".gitignore"
Content-Type: application/json
< ./.gitignore
--WebAppBoundary--
<> 2019-09-23T045805.200.json
###
I am trying to send a text and a image via HTTP POST and I always get a 400 error. I would like to use it to send a image via Telegram bot and I am using the code provided in this answer with a text and bite parameters https://stackoverflow.com/a/2793153/1970613 with small modifications.
What could be the error ?
String param = "chat_id=mi_id&photo=";
String charset = "UTF-8";
String request = "https://api.telegram.org/bot-botCOde/sendPhoto";
URL url = new URL( request );
File binaryFile = new File("/home/joseantonio/imagen.jpg");
String CRLF = "\r\n"; // Line separator required by multipart/form-data.
String boundary = Long.toHexString(System.currentTimeMillis());
HttpURLConnection conn= (HttpURLConnection) url.openConnection();
conn.setDoOutput( true );
conn.setInstanceFollowRedirects( false );
conn.setRequestMethod( "POST" );
conn.setRequestProperty( "charset", "utf-8");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
conn.setUseCaches( false );
try {
OutputStream output = conn.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF);
writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);
writer.append(CRLF).append(param).append(CRLF).flush();
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"").append(CRLF);
writer.append("Content-Type: image/jpg").append(CRLF);
writer.append("Content-Transfer-Encoding: binary").append(CRLF);
writer.append(CRLF).flush();
Files.copy(binaryFile.toPath(), output);
output.flush(); // Important before continuing with writer!
writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.
// End of multipart/form-data.
writer.append("--" + boundary + "--").append(CRLF).flush();
int responseCode2 = conn.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + request);
System.out.println("Response Code : " + responseCode2);```
I believe the fact that you are using https url is the cause of the error you are getting. You need to handle things a little different when you are submitting to an https url. See an example here
My project is to upload the image, audio files with some parameter(like description and date).
Though Google announced to use HttpURLConnection instead of httpclient. I am using HttpURLConnection.
I have an code which upload the image and audio in server folder.
But the description which I send is not received in the server.
Like this question many in Stackover flow. But I did not get exact solution.
My android code is:
FileInputStream fileInputStream = new FileInputStream(sourceFile_image);
URL url = new URL(upLoadServerUri);
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);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
//adding parameter
String description = ""+"Desceiption about the image";
// Send parameter #name
dos.writeBytes("Content-Disposition: form-data; name=\"description\"" + lineEnd);
dos.writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd);
dos.writeBytes("Content-Length: " + description.length() + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(description + lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
// Send #image
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);
And Php Code:
$description= $_POST['description'];
$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
echo "success";
} else{
echo "fail";
}
Image and audio updating successfully.
But parameter not received or I dont know how to receive the parameter in php.
Is my android and php code to send and receive parameter is correct?
Is Any other solution.
I am trying lot but not works and not getting idea too.
check this link
Android code:
String description = ""+"Desceiption about the image";
dos.writeBytes("Content-Disposition: form-data; name=\"description\"" + lineEnd);
//dos.writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd);
//dos.writeBytes("Content-Length: " + description.length() + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(description); // mobile_no is String variable
dos.writeBytes(lineEnd);
Php code:
$description =$_POST['description'];
// Send parameter #name
dos.writeBytes("Content-Disposition: form-data; name=\"name\"" + lineEnd);
That should be:
// Send parameter #description
dos.writeBytes("Content-Disposition: form-data; name=\"description\"" + lineEnd);
i want to use google speech api, i've found this https://github.com/gillesdemey/google-speech-v2/ where everything is explained well, but and im trying to rewrite it into java.
File filetosend = new File(path);
byte[] bytearray = Files.readAllBytes(filetosend);
URL url = new URL("https://www.google.com/speech-api/v2/recognize?output="+outputtype+"&lang="+lang+"&key="+key);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//method
conn.setRequestMethod("POST");
//header
conn.setRequestProperty("Content-Type", "audio/x-flac; rate=44100");
now im lost... i guess i need to add the bytearray into the request. in the example its line
--data-binary #audio/good-morning-google.flac \
but httpurlconnection class has no method for attaching binary data.
But it has getOutputStream() to which you can write your data. You may also want to call setDoOutput(true).
The code below works for me. I just used commons-io to simplify, but you can replace that:
URL url = new URL("https://www.google.com/speech-api/v2/recognize?lang=en-US&output=json&key=" + key);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "audio/x-flac; rate=16000");
IOUtils.copy(new FileInputStream(flacAudioFile), conn.getOutputStream());
String res = IOUtils.toString(conn.getInputStream());
Use multipart/form-data encoding for mixed POST content (binary and character data)
//set connection property
connection.setRequestProperty("Content-Type","multipart/form-data; boundary=" + <random-value>);
PrintWriter writer = null;
OutputStream output = connection.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
// Send binary file.
writer.append("--" + boundary).append("\r\n");
writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"").append("\r\n");
writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName()).append("\r\n");
writer.append("Content-Transfer-Encoding: binary").append("\r\n");
writer.append("\r\n").flush();
I'm trying to post a file and data to my server from an Android java script (to my php), it seems I'm pretty much there, but someone PLEASE help me, as I can't seem to format the name/value part (the FILE uploads perfect, but it doesn't send the name value :( )
JAVA:
try{
int serverResponseCode = 0;
final String upLoadServerUri = "http://myUrl/upload_file_functions.php";
String fileName = "/mnt/sdcard/myFile.dat";
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("/mnt/sdcard/myFile.dat");
// 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("file", fileName);
conn.setRequestProperty("gmail", names[0]);
conn.setRequestProperty("phn", phn);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
String data = URLEncoder.encode("gmail", "UTF-8") + "=" + URLEncoder.encode(names[0], "UTF-8");
dos.writeBytes(data);
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);
dos.writeBytes("Content-Disposition: form-data; name=\"" + names[0] + "\"" + lineEnd);
dos.writeBytes("Content-Type: text/plain"+lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(names[0]);
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){
// it worked !
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
}catch (Exception e){
}
It doesn't work, the FILE sends fine, but I can't get a freaking key/name to send ("gmail:"names[0]) I've also tried:
// 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("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("gmail", names[0]);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
DOESN'T WORK. I've tried:
dos.writeBytes("Content-Disposition: form-data; name=\"gmail\";filename=\""+ names[0] + "\"" + lineEnd);
Doesn't WORK! WTF! I've programmed for years in C++ and python, it's a simple thing! But I can't figure this out I need help, if you know how to do it PLEASE DO TELL because I've spent two days banging my head against the wall. I'm not lazy I spent 32+ f'n hours on this please I beg you..
What I WANT to happen: send the file for upload, along with the value (name=gmail value=names[0]; name=phn value=phn), so that the email is associated to the file on my server.
What IS happening: file is uploading fine, but data is not passed (the name/value pairs are not sent)
PHP:
<?php
set_time_limit(100);
//need to get email also (gmail address of user)
//************************************************
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
function Three(){
$to = 'me#email.com';
$subject = $_POST['phn'] . " " . $_POST['gmail'];
$bound_text = "file";
$bound = "--".$bound_text."\r\n";
$bound_last = "--".$bound_text."--\r\n";
$headers = "From: me#email.com\r\n";
$headers .= "MIME-Version: 1.0\r\n"
."Content-Type: multipart/mixed; boundary=\"$bound_text\"";
$message .= "If you can see this MIME than your client doesn't accept MIME types!\r\n"
.$bound;
$message .= "Content-Type: text/html; charset=\"iso-8859-1\"\r\n"
."Content-Transfer-Encoding: 7bit\r\n\r\n"
."hey my <b>good</b> friend here is a picture of regal beagle\r\n"
.$bound;
$file = file_get_contents("http://myURL/upload/myFile.dat");
$message .= "Content-Type: image/jpg; name=\"myFile.dat\"\r\n"
."Content-Transfer-Encoding: base64\r\n"
."Content-disposition: attachment; file=\"myFile.dat"\r\n"
."\r\n"
.chunk_split(base64_encode($file))
.$bound_last;
#mail($to, $subject, $message, $headers);
//delete files
$fileArray=array($_FILES["file"]["name"],"myfile.dat","myfile.dat");
foreach($fileArray as $value){
if(file_exists($value)){
unlink($value);
}
}
chdir($old_path);
}
function runAll(){
One();
Two();
Three();
}
runAll();
$randx=null;
unset($randx);
?>
PLEASE HELP! The JAVA is not sending the name='gmail' value=names[0], nor the name='phn' value=phn ..
You should really read up on a few things: HTTP (and the distinction between request header fields and the post body), and the structure of a multipart/form-data post body.
This:
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("file", fileName);
conn.setRequestProperty("gmail", names[0]);
conn.setRequestProperty("phn", phn);
sends a few request headers, which is fine for Content-Type and such, but not necessarily for the data you're posting. Lose all but the Content-Type line.
This:
dos.writeBytes(twoHyphens + boundary + lineEnd);
is the right way to start a post field (or file), you should output this for every posted field.
This:
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
signals that all fields have been sent, you should send this as the very last line.
Either use something like Wireshark to see what your final request looks like (either side will do; the device doing the request or the server handling it), or log your request so you can inspect it, and see if it is perfect. It has to be nearly perfect for the webserver/php to process it correctly.
Well, I never figured out how to send a simple string parameter with the file upload, but my workaround was to simply append the filename of the upload file to INCLUDE the string I wanted to send:
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
try{
Account[] accounts=AccountManager.get(this).getAccountsByType("com.google");
String myEmailid=accounts[0].toString(); Log.d("My email id that i want", myEmailid);
String[] names = new String[accounts.length];
for (int i = 0; i < names.length; i++) {
names[i] = accounts[i].name;
}
// THE DEVICE EMAIL ADDRESS WAS ONE OF THE DATA STRINGS I NEEDED TO SEND
File from = new File("/mnt/sdcard/","UPLOADFILE.DAT");
File to = new File("/mnt/sdcard/",names[0]+".BLOCK1."+"DATASTRING2"+".BLOCK2");
from.renameTo(to);
// DATASTRING2 is the SECOND piece of DATA I wanted to send
// SO YOU SEE I'M SIMPLY APPENDING THE UPLOAD FILE WITH THE DATA I WANT
// TO SEND WITH THE FILE, AND WHEN MY SERVER RECEIVES IT, I USE SOME SIMPLE
// PHP TO PARSE OUT WHATS BEFORE .BLOCK1. AND THEN .BLOCK2
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try{
int serverResponseCode = 0;
final String upLoadServerUri = "http://MYURL/upload_file_functions.php";
String fileName = "/mnt/sdcard/"+names[0]+".BLOCK1."+"DATASTRING2"+".BLOCK2";
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("/mnt/sdcard/"+names[0]+".BLOCK1."+"DATASTRING2"+".BLOCK2"");
// 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("Content-Type", "multipart/form-data;boundary=" + boundary);
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)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
}catch (Exception e){
}
}catch (Exception e){
}
}
Thanks for the help! (THICK WITH SARCASM..) Seriously, I have to code in python, C++, java, PHP, on linux, Android, iPhone, Windows, MAC and Ubuntu... my work has me building Triple-Boot OS box's, building apps in Android and iPhone to support my business needs, and thus I must know PHP html and the like, needed to configure my own server because I needed email-notification services, so I needed to run my own email server (Exim on Ubuntu Server), and I've had to learn all this in the past 6 months.
Forgive me if my code's not pretty, but I don't have the luxury of time, as I'm going INSANE trying to keep up in the land of AI, Object recognition, and trying to make the rent (though I've learned enough to do so..)
DC:)