application getting slower when getting data from service in KITKAT android version - android

The application is working good in lower than 4.4.2 version in android. when am running application in 4.4.2 version device application is very slow while getting/calling data from the web service.
Is anyone facing this kind problem? please help me if have solution for this.
following is my code to attachemnt uploading.
private class UploadAttachmentTask extends AsyncTask {
ProgressDialog dialog;
int result = 0;
#Override
protected void onPostExecute(Boolean res) {
super.onPostExecute(res);
if (!ApplicationData.isOffline())
dialog.dismiss();
updateData(result);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
if (!ApplicationData.isOffline()) {
dialog = new ProgressDialog(EvidenceDetailActivity.this);
dialog.setMessage("Uploading resource...");
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMax(100);
dialog.setProgress(0);
dialog.setCancelable(false);
dialog.show();
}
}
// posting image audio, video file to server
public int postMediaDataToServer(String evidenceId, File file) {
String fileName = service.createFileNameWithDate(file);
System.gc();
int result = postAttachmentToServer(fileName, file, evidenceId);
return result;
}
#SuppressWarnings("deprecation")
public int postAttachmentToServer(String fileName, File file,
String evidenceId) {
try {
System.gc();
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "----WebKitFormBoundarysNDKBMUFqqvzYWGh";
byte[] buffer;
try {
long fileSize = file.length();
int bufferSize = 1024 * 512;
FileInputStream fileInputStream = new FileInputStream(file);
URL url = new URL(CacheAPI.mediaURL());
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
//conn.setChunkedStreamingMode(bufferSize);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestProperty("X-Ecordia-Software", "ecordiApp");
List<Cookie> cookies = ApplicationData.getCookieStore()
.getCookies();
if (cookies.size() > 0)
conn.setRequestProperty("Cookie", cookies.get(0)
.getName() + "=" + cookies.get(0).getValue());
conn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(lineEnd + twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"EvidenceIdentifier\""
+ lineEnd + lineEnd);
dos.writeBytes(evidenceId + lineEnd);
dos.writeBytes(lineEnd + twoHyphens + boundary + lineEnd);
if (fileName.endsWith(".jpg")) {
dos.writeBytes("Content-Disposition: form-data; name=\"File0\"; filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes("Content-Type: image/jpeg" + lineEnd
+ lineEnd);
} else if (fileName.endsWith(".mp4")) {
dos.writeBytes("Content-Disposition: form-data; name=\"File0\"; filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes("Content-Type: video/mp4" + lineEnd
+ lineEnd);
} else if (fileName.endsWith(".3gp")) {
dos.writeBytes("Content-Disposition: form-data; name=\"File0\"; filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes("Content-Type: video/3gp" + lineEnd
+ lineEnd);
} else if (fileName.endsWith(".mov")) {
dos.writeBytes("Content-Disposition: form-data; name=\"File0\"; filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes("Content-Type: video/quicktime"
+ lineEnd + lineEnd);
} else if (fileName.endsWith(".wav")) {
dos.writeBytes("Content-Disposition: form-data; name=\"File0\"; filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes("Content-Type: audio/wav" + lineEnd
+ lineEnd);
}
buffer = new byte[bufferSize];
int bytesRead = 0;
long count = 0;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
dos.write(buffer, 0, bytesRead);
count = count + bufferSize;
publishProgress((int) ((count * 100) / fileSize));
}
dos.writeBytes(lineEnd + twoHyphens + boundary + twoHyphens
+ lineEnd);
fileInputStream.close();
dos.flush();
dos.close();
} catch (Exception e) {
e.printStackTrace();
LogService.appendLog(Log.getStackTraceString(e));
}
try {
inStream = new DataInputStream(conn.getInputStream());
#SuppressWarnings("unused")
String str;
while ((str = inStream.readLine()) != null) {
}
inStream.close();
conn.disconnect();
return 0;
} catch (Exception ioex) {
LogService.appendLog(Log.getStackTraceString(ioex));
return 2;
}
} catch (Exception e) {
LogService.appendLog(Log.getStackTraceString(e));
return 2;
} catch (OutOfMemoryError e) {
LogService.appendLog(Log.getStackTraceString(e));
return 1;
}
}
#Override
protected void onProgressUpdate(Integer... values) {
dialog.setProgress(values[0]);
}
#Override
protected Boolean doInBackground(File... params) {
try {
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
if (!ApplicationData.isOffline()) {
try {
result = postMediaDataToServer(
mCurrentEvidence.getEvidenceIdentifier(), params[0]);
} catch (Exception e) {
e.printStackTrace();
}
} else if (isOfflineEvidence) {
List<OfflineEvidence> offlineEvidences;
if (ApplicationData.isAssessor()) {
offlineEvidences = LoginActivity.assessorOfflineEvidenceDataSource
.getAllOfflineEvidences(
ApplicationData.getCandidateName(),
ApplicationData.getApiPortfolioId());
} else {
offlineEvidences = offlineDataSource
.getAllOfflineEvidences(ApplicationData
.getApiPortfolioId());
}
if (evidenceDate != null) {
for (OfflineEvidence offlineEvidence : offlineEvidences) {
if (offlineEvidence.getDate().equals(evidenceDate)) {
service.storeMediaToDataBase(offlineEvidence,
params[0]);
}
}
}
}
return true;
}
}

Related

Image not uploading to server while using GZIPOutputStream

I am able to upload image without using GZIPOutputStream to server. But i have requirement to use GZIPOutputStream. So i have used by :
public String multipartRequest(String urlTo, String post, String filepath, String filefield) throws ParseException, IOException {
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
InputStream inputStream = null;
String twoHyphens = "--";
String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****";
String lineEnd = "\r\n";
String result = "";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
String[] q = filepath.split("/");
int idx = q.length - 1;
try {
File file = new File(filepath);
FileInputStream fileInputStream = new FileInputStream(file);
// code my
byte[] data = new byte[(int) file.length()];
URL url = new URL(urlTo);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("User-Agent", "Android Multipart HTTP Client 1.0");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
// connection.setRequestProperty("Content-Encoding", "gzip");
outputStream = new DataOutputStream(connection.getOutputStream());
// outputStream.writeBytes("HTTP/1.1 200 OK\r\n");
// outputStream.writeBytes("Content-Type: application/x-gzip");
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + filefield + "\"; filename=\"" + q[idx] + ".gz" + "\""
+ lineEnd);
// outputStream.writeBytes("Content-Disposition: form-data; name=\"" + filefield + "\"; filename=\"" +
// q[idx] + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: image/jpeg" + lineEnd);
outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
// buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(data, 0, bufferSize);
while (bytesRead > 0) {
outputStream.write(data, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(data, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
// Upload POST Data
String[] posts = post.split("&");
int max = posts.length;
for (int i = 0; i < max; i++) {
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
String[] kv = posts[i].split("=");
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + kv[0] + ".gz" + "\"" + lineEnd);
// outputStream.writeBytes("Content-Disposition: form-data; name=\"" + kv[0] + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: text/plain" + lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(kv[1]);
outputStream.writeBytes(lineEnd);
}
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// For GZip outputStream //
try (GZIPOutputStream gzos = new GZIPOutputStream(outputStream)) {
gzos.write(data);
gzos.close();
Log.v("GZip", "Working");
} catch (IOException e) {
Log.v("TraceError", e.getMessage().toString());
e.printStackTrace();
}
// end
inputStream = connection.getInputStream();
result = this.convertStreamToString(inputStream);
Log.v("MYRESULT", result);
fileInputStream.close();
inputStream.close();
outputStream.flush();
outputStream.close();
return result;
} catch (Exception e) {
Log.e("MultipartRequest", "Multipart Form Upload Error");
e.printStackTrace();
return "error";
}
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
Here I am able to see
Log.v("GZip", "Working");
means file is compressed but image is not uploading to server.
I am not able to see this statement means not getting success. Also i m not getting any kind of error , warning etc nothing.
Log.v("MYRESULT", result);
So can anyone have a idea? Advanced help would be appreciated !
Finally i have solved with myself.!
I was doing mistake here !
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + kv[0] + ".gz" + "\"" + lineEnd);
I was appending ".gz" to other form data. I only needed to append file name.
Its really a silly !
You are not reading the inputstream correctly onto data. You are overwriting it on every loop. Change the code to
int totalBytesRead = 0;
bytesRead = fileInputStream.read(data, 0, data.length);
while (bytesRead > 0) {
totalBytesRead += bytesRead;
bytesRead = fileInputStream.read(data, totalBytesRead, data.length - totalBytesRead);
}
outputStream.write(data);

Android HTTP POST file upload not working with HttpUrlConnection

I am trying to upload a file to a server via HTTP POST from my device. I have two method upload1 and upload2.
Upload1 uses the HttpPost class and it works, but with bigger files it throws out of memory exception.
Upload2 uses HttpURLConnection and it does not work. (I get BAD REQUEST message from the server.) I want upload2 to work, because it uses stream to send the data and throws no out of memory exception.
I looked at the packages in wireshark, the headers are seems to be the same, however the length with upload1 is 380, with upload2 is only 94. What could be the problem?
private void upload1(File file) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url + "?recname="
+ fileName);
// ///////////////////////////////////////
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "---------------------------This is the boundary";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
FileInputStream fin = new FileInputStream(file);
byte audioData[] = new byte[(int) file.length()];
fin.read(audioData);
fin.close();
// Send a binary file
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes("Content-Type: audio/mp4" + lineEnd);
dos.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
dos.writeBytes(lineEnd);
dos.write(audioData);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
dos.flush();
dos.close();
ByteArrayInputStream content = new ByteArrayInputStream(
baos.toByteArray());
BasicHttpEntity entity = new BasicHttpEntity();
entity.setContent(content);
entity.setContentLength(baos.toByteArray().length);
httppost.addHeader("Content-Type", "multipart/form-data; boundary="
+ boundary);
httppost.setEntity(entity);
// //////////////////////////////////
HttpResponse response = httpclient.execute(httppost);
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
reader.close();
message = builder.toString();
System.out.println(message);
} catch (UnknownHostException e) {
message = "Error! Server is unreachable. Check you internet connection!";
} catch (Exception e) {
message = "error: " + e.toString();
}
}
/////////////////////////////////////////////////////////////////////////////////////////
private void upload2(File file) {
HttpURLConnection connection = null;
String pathToOurFile = file.getPath();
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "---------------------------This is the boundary";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
try {
fileInputStream = new FileInputStream(new File(pathToOurFile));
URL server_url = new URL(url+ "?recname="
+ fileName);
connection = (HttpURLConnection) server_url.openConnection();
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Enable POST method
connection.setRequestMethod("POST");
String bodyHeader = twoHyphens
+ boundary
+ lineEnd
+ "Content-Disposition: form-data; name=\"file\";filename=\""
+ fileName + "\"" + lineEnd + "Content-Type: audio/mp4"
+ lineEnd + "Content-Transfer-Encoding: binary" + lineEnd
+ lineEnd + twoHyphens + boundary + twoHyphens ;
byte[] bodyHeaderAray = bodyHeader.getBytes();
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
connection.setRequestProperty("Expect", "100-continue");
// Content-Length
int bodyHeaderSize = (int) file.length() + bodyHeaderAray.length;
System.out.println("body header size: " + bodyHeaderSize);
// connection.setFixedLengthStreamingMode(bodyHeaderSize);
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream
.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\""
+ fileName + "\"");
outputStream.writeBytes(lineEnd);
outputStream.writeBytes("Content-Type: audio/mp4" + lineEnd);
outputStream.writeBytes("Content-Transfer-Encoding: binary"
+ lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
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);
fileInputStream.close();
outputStream.flush();
outputStream.close();
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
message = serverResponseMessage;
} catch (Exception ex) {
System.out.println(ex);
}
}
According to the Problems you are getting to upload the files. you should use Multipart mechanism to upload the files to server.
httpclient-4.1.jar
httpcore-4.1.jar
httpmime-4.1.jar
apache-mime4j-0.6.1.jar
For that you need to add couple of libraries into your project and use it for HTTP connection and file data.
private boolean uploadFile(File mFile) {
boolean success = true;
String filename = mFile.getName();
MultipartEntity data_to_send = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
try {
data_to_send.addPart(
"name",
new StringBody(
filename.substring(filename.lastIndexOf("/") + 1)));
data_to_send.addPart("fileData", new FileBody(mFile));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
String responseData = ConsumeWebService.sendRequest(data_to_send,
Global.BASE_URL + serviceUrl);
if (TextUtils.isEmpty(responseData)
|| responseData.equals(ConsumeWebService.ERROR_CODE)) {
success = false;
}
} catch (Exception e) {
success = false;
e.printStackTrace();
}
return success;
}
public static String sendRequest(MultipartEntity data, String url) {
String response = "";
response = postData(url, data);
return response;
}
private static String postData(String url, MultipartEntity data) {
String strResponse = "";
try {
Log.d(Global.TAG, "Post URL is " + url);
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(data);
strResponse = httpClient.execute(httpPost,
new BasicResponseHandler());
} catch (UnsupportedEncodingException e) {
strResponse = ERROR_CODE;
e.printStackTrace();
} catch (ClientProtocolException e) {
strResponse = ERROR_CODE;
e.printStackTrace();
} catch (IOException e) {
strResponse = ERROR_CODE;
e.printStackTrace();
}
return strResponse;
}
You can build by your own your POST Request by following this w3.org docs about forms.
I think in upload2 you are missing one lineEnd where you do:
....
outputStream.writeBytes("Content-Transfer-Encoding: binary"
+ lineEnd);
After this, you have to transmit the data and it takes two lineEnds before actual data, so it should be:
....
outputStream.writeBytes("Content-Transfer-Encoding: binary"
+ lineEnd + lineEnd);
For reading files and place them in multipart/form-data structure, I suggest you this way that works for me:
FileInputStream fileInputStream=new FileInputStream(file);
byte[] bytes= new bytes[fileInputStream.getChannel().size()];
fileInputStream.read(bytes);
fileInputStream.close();
outputStream.write(bytes);
outputStream.writeBytes(lineEnd);
Hope it helps.

Cannot upload a file using HttpUrlConnection

I am trying to upload a zip file to our server along with the params using UrlConnection. This is uploading the file but it is not sending the parameters.
Here is the code.
private static final String CRLF = "\r\n"; // Line separator required by multipart/form-data.
private static final String CHARSET_UTF_8 = "UTF-8";
private static final String TWO_HYPHENS = "--";
public static void uploadReport(String filePath) {
File binaryFile = new File(filePath);
String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
String urlString = "https://mycompany.com/api/file/uad.json";
HttpsURLConnection connection = null;
DataOutputStream dataOutoutStream = null;
try {
URL url = new URL(urlString);
connection = (HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Cache-Control", "no-cache");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
OutputStream output = connection.getOutputStream();
dataOutoutStream = new DataOutputStream(output);
// Send normal param.
writeParameter(dataOutoutStream, boundary, "app_name", "My App Name");
writeParameter(dataOutoutStream, boundary, "app_version", "2.04");
// Send binary file.
writeBinaryFile(output, dataOutoutStream, boundary, binaryFile);
// End of multipart/form-data.
dataOutoutStream.writeBytes("--" + boundary + "--" + CRLF);
Log.v(tag, "response code " + connection.getResponseCode());
} catch(FileNotFoundException e) {
e.printStackTrace();
} catch(UnsupportedEncodingException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
} finally {
if (dataOutoutStream != null)
try {
dataOutoutStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here is the code for my writeParameter method
private static void writeParameter(DataOutputStream dataOutputStream, String boundary, String paramName, String paramValue) throws IOException {
dataOutputStream.writeBytes(TWO_HYPHENS + boundary + CRLF);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" + paramName + "\"" + CRLF);
dataOutputStream.writeBytes("Content-Type: text/plain; charset=" + CHARSET_UTF_8 + CRLF);
dataOutputStream.writeBytes(CRLF);
dataOutputStream.writeBytes(paramValue + CRLF);
dataOutputStream.flush();
}
Here is the writeBinaryFile method
private static void writeBinaryFile(OutputStream output, DataOutputStream dataOutputStream, String boundary, File binaryFile) throws IOException {
dataOutputStream.writeBytes(TWO_HYPHENS + boundary + CRLF);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"" + CRLF);
dataOutputStream.writeBytes("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName()) + CRLF);
dataOutputStream.writeBytes("Content-Transfer-Encoding: binary" + CRLF);
dataOutputStream.writeBytes(CRLF);
dataOutputStream.flush();
InputStream input = null;
try {
input = new FileInputStream(binaryFile);
byte[] buffer = new byte[1024];
for (int length = 0; (length = input.read(buffer)) > 0;) {
output.write(buffer, 0, length);
}
// Important! Output cannot be closed. Close of writer will close output as well.
output.flush();
} finally {
if (input != null)
input.close();
}
dataOutputStream.writeBytes(CRLF);
dataOutputStream.flush();
}
May I know what I might be doing wrong.
I did check the Stackoverflow posts here and here.

Couldn't send the image to the web server database for android

I was instructed to send a report in this format
Name=tan ah kow
Email=myemail#google.com
Contact=81234567
Block=123
Street=Tampines Central
Description=Dirty water puddle
uploadedfile=a5fa23423-4907098 (BASE64-ENCODED STRING)
index=1
Set the HTTP Header "Content-Type" as "multipart/form-data; boundary=BOUNDARY_STRING"
Form the HTTP Body Message according to the HTTP POST Specifications for multipart/form-data
FORMAT IS
--BOUNDARY_STRING\r\n
Content-Disposition: form-data; name=\"Name\"\r\n\r\n
tan ah kow\r\n
--BOUNDARY_STRING\r\n
Content-Disposition: form-data; name=\"Email\"\r\n\r\n
myemail#google.com\r\n
...
...
...
--BOUNDARY_STRING\r\n
Content-Dispostion: form-data; name=\"uploadedfile\"; filename=\"android.png\"\r\n
Content-Type: MIME-TYPE\r\n
Content-Transfer-Encoding: binary\r\n\r\n
a5fa23423-4907098a5fa23423-4907098a5fa23423-4907098a5fa23423-4907098a5fa23423-4907098a5fa23423-4907098a5fa23423-4907098\r\n
--BOUNDARY_STRING--
If there is only 1 photo uploaded, just send one http post, and set index=1.
If there are 2 photos, send two http post of the same data (name, email, contact, etc) except for uploadedfile, which should be the data for the second photo, and set index=2.
If there are 3 photos, send three http post of the same data (name, email, etc) except for uploadedfile, which should be the data of the third photo, and set index=3.
The server will handle the linking of the photos to the correct report.
Following code for send images to server but didn't work. I hope anyone can help me.
String urlFEEDBACK = "http://zendragon.sg/tampinestc/report.php";
private class NewFeedbackReportAsyncTask extends AsyncTask<HashMap<String, String>, Void, String> {
#Override
protected void onPreExecute () {
}
#Override
protected String doInBackground(HashMap<String, String>... arrHashMapParameters) {
HashMap<String, String> hashmapInput = arrHashMapParameters[0];
String strPost = "source=android";
Iterator<Entry<String, String>> it = hashmapInput.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> pairs = (Map.Entry<String, String>)it.next();
strPost += "&"+(pairs.getKey() + "=" + pairs.getValue());
it.remove();
}
String strFileData = convertPhotoToString(bmp);
String result = null;
try {
result = multipartRequest(urlFEEDBACK, strPost, strFileData);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
return result;
}
#Override
protected void onPostExecute(String result) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
showResults();
}
}
This code is to convert bitmap to BASE64-ENCODED String
protected String convertPhotoToString(Bitmap theBitMap) {
if(theBitMap == null) {
return null;
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
theBitMap.compress(CompressFormat.JPEG, 60, bos);
byte[] array = bos.toByteArray();
return android.util.Base64.encodeToString(array, android.util.Base64.NO_WRAP);
}
This is the codes that send to the server.
public String multipartRequest(String urlFEEDBACK2, String strPost, String strFileData) throws ParseException, IOException{
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
InputStream inputStream = null;
String twoHyphens = "--";
String lineEnd = "\r\n";
String boundary = "BOUNDARY_STRING";
String result = "";
try {
URL url = new URL(urlFEEDBACK2);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("User-Agent",
"Android Multipart HTTP Client 1.0");
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=\"Name\""
+ lineEnd + lineEnd + strName + lineEnd);
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"Email\""
+ lineEnd + lineEnd + strEmail + lineEnd);
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"Contact\""
+ lineEnd + lineEnd + strPhoneNo + lineEnd);
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"Block\""
+ lineEnd + lineEnd + strBLK + lineEnd);
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"Street\""
+ lineEnd + lineEnd + strStreet + lineEnd);
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"Description\""
+ lineEnd + lineEnd + strDescription + lineEnd);
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"android.png\"" + lineEnd);
outputStream.writeBytes("Content-Type: image/png" + lineEnd);
outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
outputStream.writeBytes(lineEnd);
if(bmp!=null) {
//EDITED
outputStream.writeBytes(strFileData);
//ByteArrayOutputStream baos = new ByteArrayOutputStream();
//bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
//baos.writeTo(outputStream);
//baos.close();
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens);
inputStream = connection.getInputStream();
result = this.convertStreamToString(inputStream);
// Clean up
inputStream.close();
outputStream.flush();
outputStream.close();
// Log see debug
Log.d(getString(R.string.app_name), "Result: "+ result);
checkResponse(result);
return result;
} catch (Exception e) {
Log.e("MultipartRequest", "Multipart Form Upload Error");
e.printStackTrace();
return "error";
}
}
*EDITED: *
I can't seem to see any problem with my codes to send/write the image to the web server. Hope anyone can point out what is my mistake here. I need to solve this asap as my boss keep on asking me. Hope anyone can help me out here. Any help will be appreciate. Thanks in advance.

How to Upload large files using ChunkedStreaming in android?

I need to post some large files to server. I am able to upload the files which are < 3 MB , but while i am uploading a file which is > 3 MB, it shows me the Internal server exception and server response code "500". Initially, I thought it is a server side issue but I can post the large file through iOS app(By using the same url), same way I need to implement it in android.
Here is my code --
public String postMediaDataToServer(String evidenceId, File file) {
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "----WebKitFormBoundarysNDKBMUFqqvzYWGh";
Date date = new Date();
String timestamp = dateFormat.format(date);
String fileName = file.getName();
if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) {
fileName = "image_" + timestamp + ".jpg";
} else if (fileName.endsWith(".wav")) {
fileName = "audio_" + timestamp + ".wav";
} else if (fileName.endsWith(".mp4")) {
fileName = "video_" + timestamp + ".mp4";
} else if (fileName.endsWith(".3gp")) {
fileName = "video_" + timestamp + ".3gp";
}
String response = "error";
Log.e("Image filename", fileName);
Log.e("url", ApplicationData.getBaseUrl()
+ "Media");
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
// DataInputStream inputStream = null;
String pathToOurFile = fileName;
String urlServer = ApplicationData.getBaseUrl()
+ "Media";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024;
try {
FileInputStream fileInputStream = new FileInputStream(file);
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setChunkedStreamingMode(1000*1024);
// Enable POST method
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Accept-Charset", "utf-8");
connection.setRequestProperty("X-Ecordia-Software", "ecordiApp");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary="
+ boundary);
List<Cookie> cookies = ApplicationData.getCookieStore()
.getCookies();
if (cookies.size() > 0)
connection.setRequestProperty("Cookie", cookies.get(0).getName() + "="
+ cookies.get(0).getValue());
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(lineEnd + twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"EvidenceIdentifier\""
+ lineEnd + lineEnd);
outputStream.writeBytes(evidenceId + lineEnd);
outputStream.writeBytes(lineEnd + twoHyphens + boundary + lineEnd);
if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) {
outputStream.writeBytes("Content-Disposition: form-data; name=\"File0\"; filename=\""
+ fileName + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: image/jpeg" + lineEnd + lineEnd);
} else if (fileName.endsWith(".mp4")) {
outputStream.writeBytes("Content-Disposition: form-data; name=\"File0\"; filename=\""
+ fileName + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: video/mp4" + lineEnd + lineEnd);
} else if (fileName.endsWith(".wav")) {
outputStream.writeBytes("Content-Disposition: form-data; name=\"File0\"; filename=\""
+ fileName + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: audio/wav" + lineEnd + lineEnd);
}
outputStream.writeBytes(lineEnd + twoHyphens + boundary + twoHyphens
+ lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
Log.e("Image length", bytesAvailable + "");
try {
while (bytesRead > 0) {
try {
outputStream.write(buffer, 0, bufferSize);
} catch (OutOfMemoryError e) {
e.printStackTrace();
response = "outofmemoryerror";
return response;
}
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
} catch (Exception e) {
e.printStackTrace();
response = "error";
return response;
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
Log.i("Server Response Code ", "" + serverResponseCode);
Log.i("Server Response Message", serverResponseMessage);
if (serverResponseCode == 200) {
response = "true";
}
fileInputStream.close();
outputStream.flush();
outputStream.close();
outputStream = null;
} catch (Exception ex) {
// Exception handling
response = "error";
Log.e("Send file Exception", ex.getMessage() + "");
ex.printStackTrace();
}
return response;
How to solve this issue?

Categories

Resources