The following code uploads file to the server:
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.content.FileBody;
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;
public String uploadFileForStorage(String serverUrl, String filePath) {
StringBuilder responseMsg = new StringBuilder();
try {
final File file = new File(filePath);
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is
// established.
HttpConnectionParams.setConnectionTimeout(httpParameters, UPLOAD_CONNECTION_TIME_OUT);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
HttpConnectionParams.setSoTimeout(httpParameters, UPLOAD_SOCKET_TIME_OUT);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
if (serverUrl.contains("?")) {
serverUrl = Utils.getProperUrlWithOutEncode(serverUrl);
}
HttpPost postRequest = new HttpPost(serverUrl);
FileBody bin = new FileBody(file);
CustomMultiPartEntity multipartContent = new CustomMultiPartEntity(new ProgressListener() {
@Override
public void transferred(long num) {
total = total + num;
}
});
multipartContent.addPart(CUSTOM_FILE_TAG, bin);
postRequest.setEntity(multipartContent);
HttpResponse response = httpClient.execute(postRequest);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String sResponse;
while ((sResponse = reader.readLine()) != null) {
responseMsg = responseMsg.append(sResponse);
}
} else {
responseMsg = responseMsg.append(String.valueOf(response.getStatusLine().getStatusCode()));
}
} catch (Exception e) {
isError = true;
}
return responseMsg.toString();
}
}
Files are being uploaded from Tablet SDCard. The above code works fine with multiple Android Tablets like Samsung Galaxy Note 10.1 & Micromax Funbook 10 inch but crashes while uploading files in Samsung P6200. The crash doesnot immediately occur , but after 5-10% of uploading.
Previously , the upload was working fine on Samsung P6200 too . I made the factory reset of the tablet but the crash at upload persists. Also , OutOfMemoryException is not being shown in the logcat. The log shows NullPointerException in a class file which it shouldnot. Assuming the problem to be a HeapSize issue , how can I handle the issue.
Using the above code , I am able to upload file upto 400 MB from SDCard using SIM(3G / WiFi) with Android Tablets like Samsung Galaxy Note 10.1 & Micromax Funbook 10.
should adding the following line of code help ?
HttpConnectionParams.setSocketBufferSize(httpParameters, 8192);
// or any value other than //8192