Sending file with httpurlconnection the server response is badrequest (400)? - android

I have a code that worked for me to send files to the server, I have used it in a sales app, but I want to use it in another app and it does not work for me.
String sourceFileUri = root.toString()+"/"+filename;
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(sourceFileUri);
//File sourceFile = root;
if (sourceFile.isFile()) {
try {
String upLoadServerUri =
"http://www.tucuenca.com/cspm/cargar_archivo.php";
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.setConnectTimeout (5000) ;
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE",
"multipart/form-data");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("bill", sourceFileUri);
conn.setRequestMethod("POST");
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data;
name=\"bill\";filename=\""
+ sourceFileUri + "\"" + 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();
if (serverResponseCode == 200) {
Log.i(TAG, "enviarArchivo: Cargar completa");
BufferedReader in=new BufferedReader(
new InputStreamReader(conn.getInputStream()));
StringBuffer sb= new StringBuffer("");
String line="";
while((line=in.readLine())!=null){
sb.append(line);
break;
}
resul=sb.toString();
in.close();
// showSuccessMessage("El servidor responde "+resul);
}else if(serverResponseCode==400){
Log.i(TAG, "enviarArchivo: error 400 "+resul);
// showSuccessMessage("Error en el servidor");
}
// close the streams //
fileInputStream.close();
dos.flush();
dos.close();
The server answers me with code 400, bad request, the url is active and working (http://www.tucuenca.com/cspm/cargar_archivo.php), I'm doing the tests in a huawei with android 9.
I await your comments.

Related

Add param and video(file) in multiple request by post method in Andriod

I am uploading video from android app.i am able to add only video with this code,but i am giving request with video file,but its not working.i added code with this question,help me out from this.
public int uploadFile(final String sourceFileUri) {
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String action ="action=videoUpload&id="+pHelper.getuser_id()+"&project_id="+Constants.proj_id+"&site_id="+count_et;
Log.d("bf_encoding",action);
// encode
byte[] data = new byte[0];
try {
data = action.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String value = Base64.encodeToString(data, Base64.DEFAULT);
String twoHyphens = "--";
String boundary = "*****";
String mm = "gokgo8gg4ko4gco4okg4ws4o04k44w0go4k";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
return 0;
} else {
try {
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL("https://rahumanmusic.co.in/ar_site/api/video");
Log.d("WebService", "url=" + url);
// 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("Headers","X-API-KEY=gokgo8gwskkog4ko4gco4okgo04k44w0go4k");
// conn.getHeaderFieldDate("X-API-KEY", Long.parseLong(mm));
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
Log.d("valuevalue",value);
conn.setRequestProperty("video_upload", filepathUrl1.getName());
conn.setRequestProperty("value", value);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"video_upload\";filename=\"" + filepathUrl1.getName() + "\"" + 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 (result)
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
result += line;
}
}
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Log.d("ssk", "result" + result);
return serverResponseCode;
} // End else block
}
In above code,converted base 64 string as value not passing in request. i am stuck in this task,help me out guys
Use this
library for multipart requests, i-e image, video or any other data for POST request

Uploading image multi part form from android

i have this problem that i want to upload image on a server through multi-part form but its keep giving me invalid image when i try to upload it from android but work fine from web.
this is html form which work fine.
http://letitripple.org/htmlForm.html
this is the request this html form create. (i get from chrome developer tool)
------WebKitFormBoundaryPug6xAUAlaUPbR86
Content-Disposition: form-data; name="wp-user-avatars"; filename="Desert.jpg"
Content-Type: image/jpeg
------WebKitFormBoundaryPug6xAUAlaUPbR86
Content-Disposition: form-data; name="login_id"
51
------WebKitFormBoundaryPug6xAUAlaUPbR86
Content-Disposition: form-data; name="cookie"
ali.asim#gmail.com|1473394633|vcN3CTbKi6pkAjPMKH1D9MHucPLKhw3wyeS7ViSTgGb|f5cbd913f6c3d6940066a660bac5908adb016682ce34f48e8200773eb4503c1e
------WebKitFormBoundaryPug6xAUAlaUPbR86
Content-Disposition: form-data; name="submit"
submit
------WebKitFormBoundaryPug6xAUAlaUPbR86--
This is my android code which is not working.
public AppResponse uploadImageFile(String csURL, String csFilePath)
{
AppResponse appResponse = null;
HttpURLConnection conn = null;
DataOutputStream dos = null;
ByteArrayOutputStream output = null;
InputStream inStream = null;
String Url = csURL;
String existingFileName = csFilePath;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "WebKitFormBoundaryleA9RIQsQBxW8Cgl";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
// String reponse_data = null;
int maxBufferSize = 1 * 1024 * 1024;
// String urlString = "YOUR PHP LINK FOR UPLOADING IMAGE";
try {
//------------------ CLIENT REQUEST
// FileInputStream fileInputStream = new FileInputStream(new File(existingFileName) );
// open a URL connection to the Servlet
URL url = new URL(Url);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
FileInputStream fileInputStream = new FileInputStream(new File(existingFileName));//You can get an inputStream using any IO API
byte[] bytes;
byte[] buffers = new byte[605244];
int bytesReads;
output = new ByteArrayOutputStream();
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + twoHyphens + twoHyphens + boundary);
//conn.setRequestProperty("attach1", existingFileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + twoHyphens + twoHyphens + boundary + "\r\n");
dos.writeBytes("Content-Disposition: form-data; name=\"attach1\"; filename=\"profile.jpg\"\n Content-Type: image/jpg\r\n\r\n\r\n"); // uploaded_file_name is the Name of the File to be uploaded
// 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);
Log.e("Value", "Writing");
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + twoHyphens + twoHyphens + boundary + twoHyphens);
//String strInput = dos.toString();
int responseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
fileInputStream.close();
dos.flush();
dos.close();
int nResponseCode = conn.getResponseCode();
inStream = new DataInputStream(conn.getInputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(inStream));
String line = "";
StringBuilder csResult = new StringBuilder("");
while ((line = in.readLine()) != null) {
Log.e("Debug", "Server Response " + csResult);
csResult.append(line);
}
appResponse = new AppResponse(nResponseCode, csResult.toString());
}
catch (IOException ioe) {
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
return appResponse;
}

Uploading of an Audio file on to the server

I am trying to send my audio file to the server
I am getting response code: 405
and response message : Method not Allowed
In my code the socket port is opening.
my code is:
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
// String pathToOurFile = sourceFileUri;
String urlServer = "MY SERVER URL";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
try {
Log.w("----in try---", " ");
FileInputStream fileInputStream = new FileInputStream(new File(
sourceFileUri));
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Enable POST method
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream
.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
+ sourceFileUri + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
Log.w("----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);
// Responses from the server (code and message)
serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
Log.i("Test",""+serverResponseCode+" "+serverResponseMessage);
fileInputStream.close();
outputStream.flush();
outputStream.close();
}
catch (Exception ex)
{
Log.i("test", " "+ex.getMessage());
ex.printStackTrace();
// Exception handling
}} // end upLoad2Server
Can any one help me over this.
UPDATE:
Getting 'File Not Found Exception in server response'

Android emulator file read permission

I need to upload a file from my android emulator directory ('data\data\org.mypackage\file.dat') to a remote server, but when I try to access the file it gives an error like 'error: Permission denied', I store my sqlite database in 'data\data\org.mypackage\databases\' folder , during the application startup if there is no sqlite db in that folder I copied it from my asset folder to that directory and access it from there it works perfect but in the case upload task it ask for permission why this occur? following is my uploadFile method
private void uploadFile(){
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String existingFileName="/data/data/org.mypackage/file.dat";
GeneralFunctions.comment(existingFileName);
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String responseFromServer = "";
String urlString = "http://117.231.150.213:8080/upload.jsp";
try
{
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(existingFileName) );
// open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
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=\"uploadedfile\";filename=\"" + existingFileName + "\"" + 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);
// close streams
GF.showToast("File is written");
fileInputStream.close();
dos.flush();
dos.close();
}
catch (Exception ex)
{
GeneralFunctions.exception("error: " + ex.getMessage());
}
//------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream ( conn.getInputStream() );
String str;
while (( str = inStream.readLine()) != null)
{
GeneralFunctions.comment("Server Response "+str);
}
inStream.close();
}
catch (Exception ioex){
GeneralFunctions.exception("error: " + ioex.getMessage());
}
}
Add INTERNET permission to your manifest.
If you can provide logcat then it will help more.

How to upload image and video on server using HttpUrl connection?

I want to to upload the video along with the thumbnails of that video to the server using url connection only. I am able to upload the video, but I do not know how to upload the image at the same time.
Here's my code for reference:
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String existingFileName = selectedPath;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String responseFromServer = "";
String urlString = "http://xxx/yyy/zzz/hh.php; //path of the php file on server
try
{
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(existingFileName) );
// open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
bmThumbnail = ThumbnailUtils.createVideoThumbnail(existingFileName,
Thumbnails.MICRO_KIND);
dos = new DataOutputStream( conn.getOutputStream() );
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data;name=\"uploadedfile\";filename=\"" + existingFileName +"\"" + lineEnd);
// dos.writeBytes(bmThumbnail);
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);
//check server response
int serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("file sent to:" +existingFileName,"Code:" + serverResponseCode +"Message: "+ serverResponseMessage);
// close streams
Log.e("Debug","File is written");
fileInputStream.close();
dos.flush();
dos.close();
Any suggestions? Thanks in advance.
Use multipart http post. You can use libraries to do it, or, you can compose http request manually.

Categories

Resources