Android Httpclient File Upload Data Corruption and Timeout Issues

Android httpclient file upload data corruption and timeout issues

See My Code of Image Uploader and it worked great for me
This class Uploads a file to the server plus in the end read the XML reply also.
Filter the code as per your requirement.. It worked pretty smooth for me


package com.classifieds;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

import android.util.Log;

public class Uploader
{

private String Tag = "UPLOADER";
private String urlString ;//= "YOUR_ONLINE_PHP";
HttpURLConnection conn;
String exsistingFileName ;

private void uploadImageData(String existingFileName , String urlString)
{
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
try {
// ------------------ CLIENT REQUEST

Log.e(Tag, "Inside second Method");

FileInputStream fileInputStream = new FileInputStream(new File(
exsistingFileName));

// 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);

DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

dos.writeBytes(twoHyphens + boundary + lineEnd);
dos
.writeBytes("Content-Disposition: post-data; name=uploadedfile;filename="
+ exsistingFileName + "" + lineEnd);
dos.writeBytes(lineEnd);

Log.v(Tag, "Headers are written");

// create a buffer of maximum size

int bytesAvailable = fileInputStream.available();
int maxBufferSize = 1000;
// int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bytesAvailable];

// read file and write it into form...

int bytesRead = fileInputStream.read(buffer, 0, bytesAvailable);

while (bytesRead > 0) {
dos.write(buffer, 0, bytesAvailable);
bytesAvailable = fileInputStream.available();
bytesAvailable = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bytesAvailable);
}

// send multipart form data necesssary after file data...

dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

// close streams
Log.v(Tag, "File is written");
fileInputStream.close();
dos.flush();
dos.close();

} catch (MalformedURLException ex) {
Log.e(Tag, "error: " + ex.getMessage(), ex);
}

catch (IOException ioe) {
Log.e(Tag, "error: " + ioe.getMessage(), ioe);
}

SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = null;
try {
sp = spf.newSAXParser();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

// Get the XMLReader of the SAXParser we created.
XMLReader xr = null;
try {
xr = sp.getXMLReader();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Create a new ContentHandler and apply it to the XML-Reader
MyExampleHandler1 myExampleHandler = new MyExampleHandler1();
xr.setContentHandler(myExampleHandler);

// Parse the xml-data from our URL.
try {
xr.parse(new InputSource(conn.getInputStream()));
//xr.parse(new InputSource(new java.io.FileInputStream(new java.io.File("login.xml"))));
} catch (MalformedURLException e) {
Log.d("Net Disconnected", "NetDisconeeted");
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
Log.d("Net Disconnected", "NetDisconeeted");
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
Log.d("Net Disconnected", "NetDisconeeted");
// TODO Auto-generated catch block
e.printStackTrace();
}

// Parsing has finished.

}

public Uploader(String existingFileName, boolean isImageUploading , String urlString ) {

this.exsistingFileName = existingFileName;
this.urlString = urlString;

}

class MyExampleHandler1 extends DefaultHandler
{
// ===========================================================
// Methods
// ===========================================================

@Override
public void startDocument() throws SAXException {

}

@Override
public void endDocument() throws SAXException {
// Nothing to do
}

@Override
public void startElement(String namespaceURI, String localName,
String qName, Attributes atts) throws SAXException {

}

/** Gets be called on closing tags like:
* </tag> */
@Override
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException {

}

/** Gets be called on the following structure:
* <tag>characters</tag> */
@Override
public void characters(char ch[], int start, int length) {

}
}

}

Upload video from Android to server?

Had the same issue some time ago. Here's a code.

public static int upLoad2Server(String sourceFileUri) {
String upLoadServerUri = "your remote server link";
// String [] string = sourceFileUri;
String fileName = sourceFileUri;

HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
String responseFromServer = "";

File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
Log.e("Huzza", "Source File Does not exist");
return 0;
}
try { // open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
conn = (HttpURLConnection) url.openConnection(); // Open a HTTP connection to the URL
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);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);

bytesAvailable = fileInputStream.available(); // create a buffer of maximum size
Log.i("Huzza", "Initial .available : " + bytesAvailable);

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("Upload file to server", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
// close streams
Log.i("Upload file to server", fileName + " File is written");
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
e.printStackTrace();
}
//this block will give the response of upload link
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(conn
.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
Log.i("Huzza", "RES Message: " + line);
}
rd.close();
} catch (IOException ioex) {
Log.e("Huzza", "error: " + ioex.getMessage(), ioex);
}
return serverResponseCode; // like 200 (Ok)

} // end upLoad2Server

2)call it with

int reponse=upLoad2Server(""+filepath);

Android: Sending a byte[] array via Http POST

These links might be helpful:

  • Android httpclient file upload data corruption and timeout issues
  • http://getablogger.blogspot.com/2008/01/android-how-to-post-file-to-php-server.html
  • http://forum.springsource.org/showthread.php?108546-How-do-I-post-a-byte-array

Java HTTP Client Request with defined timeout

import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

...

// set the connection timeout value to 30 seconds (30000 milliseconds)
final HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 30000);
client = new DefaultHttpClient(httpParams);

Apache HttpClient timeout

There is currently no way to set a maximum request duration of that sort: basically you want to say I don't care whether or not any specific request stage times out, but the entire request must not last longer than 15 seconds (for example).

Your best bet would be to run a separate timer, and when it expires fetch the connection manager used by the HttpClient instance and shutdown the connection, which should terminate the link. Let me know if that works for you.



Related Topics



Leave a reply



Submit