Android Httppost With Parameters And File
Solution 1:
You have to use MultipartEntity. Find online and download those two libraries: httpmime-4.0.jar and apache-mime4j-0.4.jar and then you can attach as many stuff as desired. Here is example of how to use it:
HttpPosthttpost=newHttpPost("URL_WHERE_TO_UPLOAD");
MultipartEntityentity=newMultipartEntity();
entity.addPart("myString", newStringBody("STRING_VALUE"));
entity.addPart("myImageFile", newFileBody(imageFile));
entity.addPart("myAudioFile", newFileBody(audioFile));
httpost.setEntity(entity);
HttpResponse response;
response = httpclient.execute(httpost);
and for server side you can use these entity identifier names myImageFile
, myString
and myAudioFile
.
Solution 2:
You must use a multipart http post, like in HTML forms. This can be done with an extra library. See the post Sending images using Http Post for a complete example.
Solution 3:
This works like charm for me:
publicintuploadFile(String sourceFileUri) {
String fileName=sourceFileUri;
HttpURLConnectionconn=null;
DataOutputStreamdos=null;
StringlineEnd="\r\n";
StringtwoHyphens="--";
Stringboundary="------hellojosh";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
intmaxBufferSize=1 * 1024 * 1024;
FilesourceFile=newFile(fileName);
Log.e("joshtag", "Uploading: sourcefileURI, "+fileName);
if (!sourceFile.isFile()) {
Log.e("uploadFile", "Source File not exist :"+appSingleton.getInstance().photouri);//FullPath);
runOnUiThread(newRunnable() {
publicvoidrun() {
//messageText.setText("Source File not exist :"
}
});
return0; //RETURN #1
}
else{
try{
FileInputStreamfileInputStream=newFileInputStream(sourceFile);
URLurl=newURL(upLoadServerUri);
Log.v("joshtag",url.toString());
// 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 s
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("user", user_id));
dos = newDataOutputStream(conn.getOutputStream());
//ADD Some -F Form parameters, helping method//... is declared down below
addFormField(dos, "someParameter", "someValue");
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 = newbyte[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);
Log.i("joshtag","->");
}
// 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();
StringserverResponseMessage= conn.getResponseMessage().toString();
Log.i("joshtag", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
// ------------------ read the SERVER RESPONSE
DataInputStream inStream;
try {
inStream = newDataInputStream(conn.getInputStream());
String str;
while ((str = inStream.readLine()) != null) {
Log.e("joshtag", "SOF Server Response" + str);
}
inStream.close();
}
catch (IOException ioex) {
Log.e("joshtag", "SOF error: " + ioex.getMessage(), ioex);
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
if(serverResponseCode == 200){
//Do something
}//END IF Response code 200
dialog.dismiss();
}//END TRY - FILE READ catch (MalformedURLException ex) {
ex.printStackTrace();
Log.e("joshtag", "UL error: " + ex.getMessage(), ex);
} //CATCH - URL Exceptioncatch (Exception e) {
e.printStackTrace();
Log.e("Upload file to server Exception", "Exception : "+ e.getMessage(), e);
} //return serverResponseCode; //after try
}//END ELSE, if file exists.
}
publicstaticStringlineEnd="\r\n";
publicstaticStringtwoHyphens="--";
publicstaticStringboundary="------------------------afb19f4aeefb356c";
publicstaticvoidaddFormField(DataOutputStream dos, String parameter, String value){
try {
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\""+parameter+"\"" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(value);
dos.writeBytes(lineEnd);
}
catch(Exception e){
}
}
UPDATE: If you need to send parameters along with the file, use:
conn.setRequestProperty("someParameter","someValue")
//oraddFormField(DataOutputStream dos, String parameter, String value)
...as shown in the code above. One or the other should work, if the server you are trying to connect to is not completely known to you.
Solution 4:
be careful
MultiPartEntity
and BasicNameValuePair
are deprected .
So here is the new way to do it! And you only need httpcore.jar(latest)
and httpmime.jar(latest)
download them from Apache site.
try
{
HttpClientclient=newDefaultHttpClient();
HttpPostpost=newHttpPost(URL);
MultipartEntityBuilderentityBuilder= MultipartEntityBuilder.create();
entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
entityBuilder.addTextBody(USER_ID, userId);
entityBuilder.addTextBody(NAME, name);
entityBuilder.addTextBody(TYPE, type);
entityBuilder.addTextBody(COMMENT, comment);
entityBuilder.addTextBody(LATITUDE, String.valueOf(User.Latitude));
entityBuilder.addTextBody(LONGITUDE, String.valueOf(User.Longitude));
if(file != null)
{
entityBuilder.addBinaryBody(IMAGE, file);
}
HttpEntityentity= entityBuilder.build();
post.setEntity(entity);
HttpResponseresponse= client.execute(post);
HttpEntityhttpEntity= response.getEntity();
result = EntityUtils.toString(httpEntity);
Log.v("result", result);
}
catch(Exception e)
{
e.printStackTrace();
}
Solution 5:
use this async Task.
classhttpUploader2extendsAsyncTask<Void, Void, Void> {
privatefinalstaticStringboundary="*****M9J_cfALt*****";
privatefinalstaticStringmultiPartFormData="multipart/form-data;boundary=" + boundary;
@Overrideprotected Void doInBackground(Void... params) {
HttpURLConnectionurlConnection=null;
try {
URLurl=newURL("http://192.168.43.20/test.php");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setConnectTimeout(5000);
urlConnection.setRequestProperty("Connection", "Keep-Alive");
urlConnection.setRequestProperty("Cache-Control", "no-cache");
urlConnection.setRequestProperty("Content-Type", multiPartFormData);
urlConnection.setUseCaches( false );
urlConnection.setChunkedStreamingMode(0);
DataOutputStreamrequest=newDataOutputStream(urlConnection.getOutputStream());
writeField(request,"hellow","world");
writeFile(request,"file1","testfilename.txt","this is file content as string".getBytes(StandardCharsets.UTF_8));
writeField(request,"testtt","valueeee");
writeFile(request,"file2","testfilename2222.txt","this is file content as string".getBytes(StandardCharsets.UTF_8));
request.flush();
request.close();
intcode= urlConnection.getResponseCode();
if (code == HTTP_OK) {
//Log.d("@#$","Connected");BufferedReaderrd=newBufferedReader(newInputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
Log.i("@#$", line);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
returnnull;
}
privatevoidwriteField(DataOutputStream request,String name,String value){
Stringout="\r\n--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"" + name +"\"";
out += "\r\n\r\n" + value;
try {
request.write(out.getBytes(StandardCharsets.UTF_8));
} catch (IOException ignored) {}
}
privatevoidwriteFile(DataOutputStream request,String name,String value,byte[] filedata){
Stringout="\r\n--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"" + name +"\"; filename=\"" + value + "\"";
out += "\r\n\r\n";
try {
request.write(out.getBytes(StandardCharsets.UTF_8));
request.write(filedata);
} catch (IOException ignored) {}
}
}
Use this php for testing(test.php) -
<?php
var_dump($_REQUEST);
echo"--------UPLOADED FILES--------\n";
var_dump($_FILES);
?>
I am using Android Pie on real testing device so need to declare this in manifest otherwise cannot connect-
<applicationandroid:usesCleartextTraffic="true"..
/></application>
using xampp for testing php server. but you cant access it directly on your phone(real testing device). for that , first connect your PC to device hotspot. then in apache's httpd.txt - add Require all granted.
then to get ip address of your xampp for that hotspot network, write ipconfig and look for ipv4 address.
Post a Comment for "Android Httppost With Parameters And File"