Upload of some file fails using HttpClient - android

I am trying to upload images as well as videos to my external server from the app. I Googled and found out HttpClient procedure is a good one, so I downloaded the library and execute the following code which normally works well for every file however for some videos, it does not upload the video.
public void executeMultipartPost(String uri) throws Exception {
try {
File file = new File(uri);
Uri imageUri = Uri.fromFile(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] data = readBytes(imageUri);
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(
"http://example.com/ccs-business/upload.php");
ByteArrayBody bab = new ByteArrayBody(data, file.getName());
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("uploaded_video", bab);
reqEntity.addPart("number", new StringBody("123456"));
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
Log.v("ONMESSAGE", "Response: " + s);
dialog.dismiss();
} catch (Exception e) {
// handle exception here
Log.e(e.getClass().getName(), e.getMessage());
dialog.dismiss();
}
}
public byte[] readBytes(Uri uri) throws IOException {
InputStream inputStream = getContentResolver().openInputStream(uri);
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}
My requirement is to upload up to 20mb file.

I Have tired Uploading files with below code attached and worked fine :
public class UploadService extends IntentService {
/**
* Utility method that creates the intent that starts the background
* file upload service.
*
* #param task object containing the upload request
* #throws IllegalArgumentException if one or more arguments passed are invalid
* #throws MalformedURLException if the server URL is not valid
*/
public static void startUpload(final UploadRequest task)
throws IllegalArgumentException, MalformedURLException {
if (task == null) {
throw new IllegalArgumentException("Can't pass an empty task!");
} else {
task.validate();
final Intent intent = new Intent(UploadService.class.getName());
intent.setAction(ACTION_UPLOAD);
intent.putExtra(PARAM_NOTIFICATION_CONFIG, task.getNotificationConfig());
intent.putExtra(PARAM_ID, task.getUploadId());
intent.putExtra(PARAM_URL, task.getServerUrl());
intent.putExtra(PARAM_METHOD, task.getMethod());
intent.putParcelableArrayListExtra(PARAM_FILES, task.getFilesToUpload());
intent.putParcelableArrayListExtra(PARAM_REQUEST_HEADERS, task.getHeaders());
intent.putParcelableArrayListExtra(PARAM_REQUEST_PARAMETERS, task.getParameters());
task.getContext().startService(intent);
}
}
public UploadService() {
super(SERVICE_NAME);
}
#Override
public void onCreate() {
super.onCreate();
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notification = new NotificationCompat.Builder(this);
PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
}
#Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
final String action = intent.getAction();
if (ACTION_UPLOAD.equals(action)) {
notificationConfig = intent.getParcelableExtra(PARAM_NOTIFICATION_CONFIG);
final String uploadId = intent.getStringExtra(PARAM_ID);
final String url = intent.getStringExtra(PARAM_URL);
final String method = intent.getStringExtra(PARAM_METHOD);
final ArrayList<FileToUpload> files = intent.getParcelableArrayListExtra(PARAM_FILES);
final ArrayList<NameValue> headers = intent.getParcelableArrayListExtra(PARAM_REQUEST_HEADERS);
final ArrayList<NameValue> parameters = intent.getParcelableArrayListExtra(PARAM_REQUEST_PARAMETERS);
lastPublishedProgress = 0;
wakeLock.acquire();
try {
createNotification();
handleFileUpload(uploadId, url, method, files, headers, parameters);
} catch (Exception exception) {
broadcastError(uploadId, exception);
} finally {
wakeLock.release();
}
}
}
}
private void handleFileUpload(final String uploadId,
final String url,
final String method,
final ArrayList<FileToUpload> filesToUpload,
final ArrayList<NameValue> requestHeaders,
final ArrayList<NameValue> requestParameters)
throws IOException {
final String boundary = getBoundary();
final byte[] boundaryBytes = getBoundaryBytes(boundary);
HttpURLConnection conn = null;
OutputStream requestStream = null;
try {
conn = getMultipartHttpURLConnection(url, method, boundary);
setRequestHeaders(conn, requestHeaders);
requestStream = conn.getOutputStream();
setRequestParameters(requestStream, requestParameters, boundaryBytes);
uploadFiles(uploadId, requestStream, filesToUpload, boundaryBytes);
final byte[] trailer = getTrailerBytes(boundary);
requestStream.write(trailer, 0, trailer.length);
final int serverResponseCode = conn.getResponseCode();
final String serverResponseMessage = conn.getResponseMessage();
broadcastCompleted(uploadId, serverResponseCode, serverResponseMessage);
} finally {
closeOutputStream(requestStream);
closeConnection(conn);
}
}
private String getBoundary() {
final StringBuilder builder = new StringBuilder();
builder.append("---------------------------")
.append(System.currentTimeMillis());
return builder.toString();
}
private byte[] getBoundaryBytes(final String boundary)
throws UnsupportedEncodingException {
final StringBuilder builder = new StringBuilder();
builder.append(NEW_LINE)
.append(TWO_HYPHENS)
.append(boundary)
.append(NEW_LINE);
return builder.toString().getBytes("US-ASCII");
}
private byte[] getTrailerBytes(final String boundary)
throws UnsupportedEncodingException {
final StringBuilder builder = new StringBuilder();
builder.append(NEW_LINE)
.append(TWO_HYPHENS)
.append(boundary)
.append(TWO_HYPHENS)
.append(NEW_LINE);
return builder.toString().getBytes("US-ASCII");
}
private HttpURLConnection getMultipartHttpURLConnection(final String url,
final String method,
final String boundary)
throws IOException {
final HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setChunkedStreamingMode(0);
conn.setRequestMethod(method);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
return conn;
}
private void setRequestHeaders(final HttpURLConnection conn,
final ArrayList<NameValue> requestHeaders) {
if (!requestHeaders.isEmpty()) {
for (final NameValue param : requestHeaders) {
conn.setRequestProperty(param.getName(), param.getValue());
}
}
}
private void setRequestParameters(final OutputStream requestStream,
final ArrayList<NameValue> requestParameters,
final byte[] boundaryBytes)
throws IOException, UnsupportedEncodingException {
if (!requestParameters.isEmpty()) {
for (final NameValue parameter : requestParameters) {
requestStream.write(boundaryBytes, 0, boundaryBytes.length);
byte[] formItemBytes = parameter.getBytes();
requestStream.write(formItemBytes, 0, formItemBytes.length);
}
}
}
private void uploadFiles(final String uploadId,
final OutputStream requestStream,
final ArrayList<FileToUpload> filesToUpload,
final byte[] boundaryBytes)
throws UnsupportedEncodingException,
IOException,
FileNotFoundException {
final long totalBytes = getTotalBytes(filesToUpload);
long uploadedBytes = 0;
for (FileToUpload file : filesToUpload) {
requestStream.write(boundaryBytes, 0, boundaryBytes.length);
byte[] headerBytes = file.getMultipartHeader();
requestStream.write(headerBytes, 0, headerBytes.length);
final InputStream stream = file.getStream();
byte[] buffer = new byte[BUFFER_SIZE];
long bytesRead;
try {
while ((bytesRead = stream.read(buffer, 0, buffer.length)) > 0) {
requestStream.write(buffer, 0, buffer.length);
uploadedBytes += bytesRead;
broadcastProgress(uploadId, uploadedBytes, totalBytes);
}
} finally {
closeInputStream(stream);
}
}
}
private long getTotalBytes(final ArrayList<FileToUpload> filesToUpload) {
long total = 0;
for (FileToUpload file : filesToUpload) {
total += file.length();
}
return total;
}
private void closeInputStream(final InputStream stream) {
if (stream != null) {
try {
stream.close();
} catch (Exception exc) { }
}
}
private void closeOutputStream(final OutputStream stream) {
if (stream != null) {
try {
stream.flush();
stream.close();
} catch (Exception exc) { }
}
}
private void closeConnection(final HttpURLConnection connection) {
if (connection != null) {
try {
connection.disconnect();
} catch (Exception exc) { }
}
}
private void broadcastProgress(final String uploadId, final long uploadedBytes, final long totalBytes) {
final int progress = (int) (uploadedBytes * 100 / totalBytes);
if (progress <= lastPublishedProgress) return;
lastPublishedProgress = progress;
updateNotificationProgress(progress);
final Intent intent = new Intent(BROADCAST_ACTION);
intent.putExtra(UPLOAD_ID, uploadId);
intent.putExtra(STATUS, STATUS_IN_PROGRESS);
intent.putExtra(PROGRESS, progress);
sendBroadcast(intent);
}
private void broadcastCompleted(final String uploadId, final int responseCode, final String responseMessage) {
final String filteredMessage;
if (responseMessage == null) {
filteredMessage = "";
} else {
filteredMessage = responseMessage;
}
if (responseCode >= 200 && responseCode <= 299)
updateNotificationCompleted();
else
updateNotificationError();
final Intent intent = new Intent(BROADCAST_ACTION);
intent.putExtra(UPLOAD_ID, uploadId);
intent.putExtra(STATUS, STATUS_COMPLETED);
intent.putExtra(SERVER_RESPONSE_CODE, responseCode);
intent.putExtra(SERVER_RESPONSE_MESSAGE, filteredMessage);
sendBroadcast(intent);
}
private void broadcastError(final String uploadId, final Exception exception) {
updateNotificationError();
final Intent intent = new Intent(BROADCAST_ACTION);
intent.setAction(BROADCAST_ACTION);
intent.putExtra(UPLOAD_ID, uploadId);
intent.putExtra(STATUS, STATUS_ERROR);
intent.putExtra(ERROR_EXCEPTION, exception);
sendBroadcast(intent);
}
private void createNotification() {
notification.setContentTitle(notificationConfig.getTitle())
.setContentText(notificationConfig.getMessage())
.setSmallIcon(notificationConfig.getIconResourceID())
.setProgress(100, 0, true)
.setOngoing(true);
startForeground(UPLOAD_NOTIFICATION_ID, notification.build());
}
private void updateNotificationProgress(final int progress) {
notification.setContentTitle(notificationConfig.getTitle())
.setContentText(notificationConfig.getMessage())
.setSmallIcon(notificationConfig.getIconResourceID())
.setProgress(100, progress, false)
.setOngoing(true);
startForeground(UPLOAD_NOTIFICATION_ID, notification.build());
}
private void updateNotificationCompleted() {
stopForeground(notificationConfig.isAutoClearOnSuccess());
if (!notificationConfig.isAutoClearOnSuccess()) {
notification.setContentTitle(notificationConfig.getTitle())
.setContentText(notificationConfig.getCompleted())
.setSmallIcon(notificationConfig.getIconResourceID())
.setProgress(0, 0, false)
.setOngoing(false);
notificationManager.notify(UPLOAD_NOTIFICATION_ID_DONE, notification.build());
}
}
private void updateNotificationError() {
stopForeground(false);
notification.setContentTitle(notificationConfig.getTitle())
.setContentText(notificationConfig.getError())
.setSmallIcon(notificationConfig.getIconResourceID())
.setProgress(0, 0, false)
.setOngoing(false);
notificationManager.notify(UPLOAD_NOTIFICATION_ID_DONE, notification.build());
}
}
For compelete Source code refer this

Related

How to show upload Progress for multiple uploads separately - Android

How should can I show progress bar for each file I upload in android using an upload button, something like this:
I have tried doing so using services and notification but I would like to show progress in the UI itself.
Any Code Sample will help.
I am using the following Class for multipart upload:
public class MultipartUtility
{
FileUploadListener listener;
private static final int BUFFER_SIZE = 1024;
private static final int TIME_OUT = 3 * 60 * 1000;
private final String boundary;
private static final String LINE_FEED = "\r\n";
private HttpURLConnection httpConn;
private String charset;
private OutputStream outputStream;
private PrintWriter writer;
public int statusCode;
public String mURL;
public interface FileUploadListener {
void onUpdateProgress(int percentage, long kb);
boolean isCanceled();
}
/**
* This constructor initializes a new HTTP POST request with content type
* is set to multipart/form-data
*
* #param requestURL
* #param charset
* #throws IOException
*/
public MultipartUtility(Context context, String requestURL, String charset, FileUploadListener listener)
throws IOException {
this.charset = charset;
this.listener = listener;
mURL = requestURL;
// creates a unique boundary based on time stamp
boundary = "" + System.currentTimeMillis() + "";
URL url = new URL(requestURL);
httpConn = null;
if (url.getProtocol().toLowerCase().equals("https")) {
trustAllHosts();
HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
https.setHostnameVerifier(new HostnameVerifier() {
#Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
httpConn = https;
} else {
httpConn = (HttpURLConnection) url.openConnection();
}
// httpConn.setConnectTimeout(TIME_OUT);
//httpConn.setReadTimeout(TIME_OUT);
httpConn.setUseCaches(false);
httpConn.setDoOutput(true); // indicates POST method
httpConn.setDoInput(true);
httpConn.setChunkedStreamingMode(BUFFER_SIZE);
httpConn.setRequestMethod("POST");
Storage storage = new Storage(context);
httpConn.setRequestProperty("x-auth", storage.readString("user_token"));
httpConn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
httpConn.setRequestProperty("Connection", "Keep-Alive");
outputStream = httpConn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
true);
}
private static void trustAllHosts() {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
}};
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Adds a form field to the request
*
* #param name field name
* #param value field value
*/
public void addFormField(String name, String value) {
writer.append("--" + boundary).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name=\"" + name + "\"")
.append(LINE_FEED);
writer.append("Content-Type: text/plain; charset=" + charset).append(
LINE_FEED);
writer.append(LINE_FEED);
writer.append(value).append(LINE_FEED);
writer.flush();
}
/**
* Adds a upload file section to the request
*
* #param fieldName name attribute in <input type="file" name="..." />
* #param uploadFile a File to be uploaded
* #throws IOException
*/
private long lastProgressUpdateTime = 0;
public void addFilePart(String fieldName, File uploadFile)
throws IOException {
String fileName = uploadFile.getName();
writer.append("--" + boundary).append(LINE_FEED);
writer.append(
"Content-Disposition: form-data; name=\"" + fieldName
+ "\"; filename=\"" + fileName + "\"")
.append(LINE_FEED);
writer.append(
"Content-Type: "
+ URLConnection.guessContentTypeFromName(fileName))
.append(LINE_FEED);
writer.append("charset=" + charset).append(
LINE_FEED);
writer.append(LINE_FEED);
writer.flush();
outputStream.flush();
byte[] buffer = new byte[BUFFER_SIZE];
try {
final FileInputStream inputStream = new FileInputStream(uploadFile);
long totalRead = 0;
long totalSize = uploadFile.length();
int read;
while ((read = inputStream.read(buffer)) > 0) {
totalRead += read;
int percentage = (int) ((totalRead / (float) totalSize) * 100);
outputStream.write(buffer, 0, read);
long now = System.currentTimeMillis();
if (lastProgressUpdateTime == 0 || lastProgressUpdateTime < now - 100) {
lastProgressUpdateTime = now;
Log.e("", totalRead + " " + " " + percentage);
if (listener != null)
this.listener.onUpdateProgress(percentage, totalRead);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
outputStream.flush();
}
writer.append(LINE_FEED);
writer.flush();
}
/**
* Adds a header field to the request.
*
* #param name - name of the header field
* #param value - value of the header field
*/
public void addHeaderField(String name, String value) {
writer.append(name + ": " + value).append(LINE_FEED);
writer.flush();
}
/**
* Completes the request and receives response from the server.
*
* #return a list of Strings as response in case the server returned
* status OK, otherwise an exception is thrown.
* #throws IOException
*/
public String Execute() throws IOException {
String responses = "";
writer.append(LINE_FEED).flush();
writer.append("--" + boundary + "--").append(LINE_FEED);
writer.close();
StringBuilder sb = new StringBuilder();
try {
// checks server's status code first
statusCode = httpConn.getResponseCode();
//responses = ;
sb.append("" + Helpers.convertStreamToString(httpConn.getInputStream()) + "\n");
if (statusCode == HttpURLConnection.HTTP_OK) {
httpConn.disconnect();
}
responses = sb.toString();
return responses;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
sb = new StringBuilder();
sb.append("" + Helpers.convertStreamToString(httpConn.getErrorStream()) + "\n");
responses = sb.toString();
}
return responses;
}
}
Create a singleton design for this and for every downloading file create an entry in HashMap entry with key value. For example for file1 there should be a key and value should be its updated progress. And update that entry according to file upload progress(when the call back of on progress update receive) against the key. And also update the progress bar from that hash map according to key.Because your hash map will always have updated values. Hope that helps.
In one of my project I implemented the same thing. I am sharing that now
Create download service
public class DownloadService extends IntentService {
public DownloadService() {
super("DownloadService");
}
#Override
protected void onHandleIntent(Intent intent) {
String rhymeName = intent.getStringExtra(Constants.RHYME_NAME);
String URL = intent.getStringExtra(Constants.URL);
downloadRhyme(rhymeName, URL);
}
private void sendMyBroadCast(long currentProgress, long totalVideoSize, String rhymeName) {
Intent intentUpdate = new Intent();
intentUpdate.setAction(Constants.ACTION_MYUPDATE);
intentUpdate.addCategory(Intent.CATEGORY_DEFAULT);
intentUpdate.putExtra(Constants.UPDATED_VALUES, currentProgress);
intentUpdate.putExtra(Constants.TOTAL_VIDEO_SIZE, totalVideoSize);
intentUpdate.putExtra(Constants.RHYME_NAME, rhymeName);
sendBroadcast(intentUpdate);
}
private void registerMyTaskCompletedListener(ITaskCompletedListener taskCompletedListener, boolean successful, String rhymeName) {
if (successful)
taskCompletedListener.taskCompleted(rhymeName);
else
taskCompletedListener.taskFailed(rhymeName);
}
private final void downloadRhyme(String rhymeName, String URL) {
boolean successful = false;
URL downloadURL = null;
HttpURLConnection httpURLConnection = null;
InputStream inputStream = null;
FileOutputStream fileOutputStream = null;
File file = null;
try {
downloadURL = new URL(URL);
httpURLConnection = (HttpURLConnection) downloadURL.openConnection();
int responseCode = httpURLConnection.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK)
return;
inputStream = httpURLConnection.getInputStream();
file = AppUtility.getInternalDirectoryForRhymes(this, rhymeName);
fileOutputStream = new FileOutputStream(file);
int read = -1;
long totalRead =0 ;
int totalLength = httpURLConnection.getContentLength();
byte [] buffer = new byte[1024];
while ((read = inputStream.read(buffer)) != -1) {
totalRead += read;
fileOutputStream.write(buffer, 0, read);
sendMyBroadCast(totalRead, totalLength, rhymeName);
}
successful = true;
UrduRhymesActivity.getInstance().unregisterMyReceiver();
callListener(successful, rhymeName);
} catch (Exception e) {
if (e instanceof SocketTimeoutException) {
ProgressReceiver.showSocketConnectionDialogue();
}
callListener(successful, rhymeName);
} finally {
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void callListener(boolean successful, String rhymeName) {
ITaskCompletedListener taskCompletedListener = new ProgressReceiver();
registerMyTaskCompletedListener(taskCompletedListener, successful, rhymeName);
}
}
Below is the progress receiver
public class ProgressReceiver extends BroadcastReceiver implements ITaskCompletedListener {
#Override
public void onReceive(Context context, Intent intent) {
long currentProgress = intent.getLongExtra(Constants.UPDATED_VALUES, 0);
long totalSize = intent.getLongExtra(Constants.TOTAL_VIDEO_SIZE, 0);
String rhymeName = intent.getStringExtra(Constants.RHYME_NAME);
ProgressbarDetails progressbarDetails = ProgressbarDetails.getProgressDetail(rhymeName);
if (progressbarDetails != null) {
int updates = ((int) ((currentProgress / (float) totalSize) * 100));
progressbarDetails.prgProgressBar.setVisibility(View.VISIBLE);
progressbarDetails.prgProgressBar.setProgress(updates);
LogUtility.infoLog("current downloaded file size is " + currentProgress);
LogUtility.infoLog("total file size " + totalSize);
LogUtility.infoLog("After conversion " + updates);
}
}
#Override
public void taskCompleted(String rhymeName) {
runThread(rhymeName);
}
private void runThread(final String rhymeName) {
UrduRhymesActivity.getInstance().runOnUiThread(new Runnable() {
#Override
public void run() {
ProgressbarDetails progressbarDetails = ProgressbarDetails.getProgressDetail(rhymeName);
progressbarDetails.download_btn_settings.setBackgroundResource(R.mipmap.btn_play);
progressbarDetails.prgProgressBar.setVisibility(View.GONE);
ProgressbarDetails.deleteUpdateProgressDetail(rhymeName);
}
});
}
public static void showSocketConnectionDialogue() {
UrduRhymesActivity.getInstance().runOnUiThread(new Runnable() {
#Override
public void run() {
//[Case:When server is down]
AppUtility.showConnectionDialoge(UrduRhymesActivity.sUrduRhymesActivity);
}
});
}
#Override
public void taskFailed(String rhymeName) {
boolean deleteStatus = false;
if (rhymeName != null)
deleteStatus = AppUtility.deleteFileFromInternalDirectory(MyApplication.getAppContext(), rhymeName);
if (deleteStatus)
LogUtility.infoLog("file deleted Successfully");
else LogUtility.infoLog("File not deleted");
ProgressbarDetails.deleteUpdateProgressDetail(rhymeName);
}
}
Here is the main code that keeps track of downloading status.
public class ProgressbarDetails {
public ProgressBar prgProgressBar;
public int progress;
public LinearLayout download_btn_settings;
private static HashMap<String, ProgressbarDetails> progressMapper = null;
public static HashMap<String, ProgressbarDetails> getProgressMapper() {
if(progressMapper == null)
progressMapper = new HashMap<>();
return progressMapper;
}
public static ProgressbarDetails getProgressDetail(String rhymeName) {
Object obj = getProgressMapper().get(rhymeName);
ProgressbarDetails ProgressbarDetails = null;
if (obj != null)
ProgressbarDetails = (ProgressbarDetails) obj;
return ProgressbarDetails;
}
public static void addUpdateProgressDetail(String rhymeName, ProgressbarDetails prgBarDetail) {
progressMapper = getProgressMapper();
progressMapper.put(rhymeName, prgBarDetail);
}
public static void deleteUpdateProgressDetail(String rhymeName) {
progressMapper = getProgressMapper();
if(progressMapper.containsKey(rhymeName))
progressMapper.remove(rhymeName);
}
}
Hope that helps.
This is how I would do it:
Create a RecyclerView to hold each upload progress row
Upon starting a new upload - add new item (row) to the RecyclerView
You need to keep some kind of mapping between the RecyclerView row position and the upload task it represents (HashMap is a good option)
Listen to the upload progress of your task (I see you have a listener already implemented) and when an update arrives - query to HashMap from step 3 to check which RecyclerView row you need to update.
Update the RecyclerView row with the position from step 4.
Some resources to get you started:
Working with Recycler View
How to add new item to RecyclerView
How to update/refresh specific item in RecyclerView
Java HashMap class

Intent Service stopping before finishing the task?

I have a IntentService I am doing some task in another thread in
onHandleIntent(Intent intent)
Why is the IntentService stopping before performing the operation(task)?
Here is my code:
public class SampleIntentService extends IntentService {
public static final int DOWNLOAD_ERROR = 10;
public static final int DOWNLOAD_SUCCESS = 11;
public SampleIntentService() {
super(SampleIntentService.class.getName());
}
#Override
protected void onHandleIntent(Intent intent) {
final String url = intent.getStringExtra("url");
final ResultReceiver receiver = intent.getParcelableExtra("receiver");
final Bundle bundle = new Bundle();
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
return downloadFile(url, receiver);
}
#Override
protected void onPostExecute(String filePath) {
super.onPostExecute(filePath);
bundle.putString("filePath", filePath);
receiver.send(DOWNLOAD_SUCCESS, bundle);
}
};
}
private String downloadFile(String url, ResultReceiver receiver) {
File downloadFile = new File(Environment.getExternalStorageDirectory() + File.pathSeparator + "test.png");
if (downloadFile.exists())
downloadFile.delete();
try {
downloadFile.createNewFile();
URL downloadURL = new URL(url);
HttpURLConnection conn = (HttpURLConnection) downloadURL
.openConnection();
int responseCode = conn.getResponseCode();
if (responseCode != 200)
throw new Exception("Error in connection");
InputStream is = conn.getInputStream();
FileOutputStream os = new FileOutputStream(downloadFile);
byte buffer[] = new byte[1024];
int byteCount;
while ((byteCount = is.read(buffer)) != -1) {
os.write(buffer, 0, byteCount);
}
os.close();
is.close();
String filePath = downloadFile.getPath();
return filePath;
} catch (Exception e) {
receiver.send(DOWNLOAD_ERROR, Bundle.EMPTY);
e.printStackTrace();
}
return null;
}
}
As per the Docs:
abstract void onHandleIntent(Intent intent)
This method is invoked on the worker thread with a request to process.
Since this method is already invoked on worker thread you don't need to start another thread.
If you do that, the onHandleIntent(Intent intent) will return and the IntentService will think the task is done and it will stop itself.
Source: onHandleIntent
Here is the updated code :
public class SampleIntentService extends IntentService {
public static final int DOWNLOAD_ERROR = 10;
public static final int DOWNLOAD_SUCCESS = 11;
public SampleIntentService() {
super(SampleIntentService.class.getName());
}
#Override
protected void onHandleIntent(Intent intent) {
final String url = intent.getStringExtra("url");
final ResultReceiver receiver = intent.getParcelableExtra("receiver");
final Bundle bundle = new Bundle();
String filePath = downloadFile(url, receiver);
bundle.putString("filePath", filePath);
receiver.send(DOWNLOAD_SUCCESS, bundle);
}
private String downloadFile(String url, ResultReceiver receiver) {
File downloadFile = new File(Environment.getExternalStorageDirectory() + File.pathSeparator + "test.png");
if (downloadFile.exists())
downloadFile.delete();
try {
downloadFile.createNewFile();
URL downloadURL = new URL(url);
HttpURLConnection conn = (HttpURLConnection) downloadURL
.openConnection();
int responseCode = conn.getResponseCode();
if (responseCode != 200)
throw new Exception("Error in connection");
InputStream is = conn.getInputStream();
FileOutputStream os = new FileOutputStream(downloadFile);
byte buffer[] = new byte[1024];
int byteCount;
while ((byteCount = is.read(buffer)) != -1) {
os.write(buffer, 0, byteCount);
}
os.close();
is.close();
String filePath = downloadFile.getPath();
return filePath;
} catch (Exception e) {
receiver.send(DOWNLOAD_ERROR, Bundle.EMPTY);
e.printStackTrace();
}
return null;
}

Download a file with no extension from a server

I'm try to download a mp3 file from following URL. I found lot of articles and examples regarding file download. Those examples are based on URLs that end with a file extension, e.g.:- yourdomain.com/filename.mp3 but I want to download a file from following url which typically does not end with file extension.
youtubeinmp3.com/download/get/?i=1gsE32jF0aVaY0smDVf%2BmwnIZPrMDnGmchHBu0Hovd3Hl4NYqjNdym4RqjDSAis7p1n5O%2BeXmdwFxK9ugErLWQ%3D%3D
**Please note that I use the above url as-is without using Stackoverflow url formatting method to easily understand the question.
** I have tried the #Arsal Imam's solution as follows still not working
btnShowProgress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// starting new Async Task
File cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"Folder Name");
if(!cacheDir.exists())
cacheDir.mkdirs();
File f=new File(cacheDir,"ddedddddd.mp3");
saveDir=f.getPath();
new DownloadFileFromURL().execute(fileURL);
}
});
and the async task code is as follows
class DownloadFileFromURL extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
#Override
protected String doInBackground(String... f_url) {
try{
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
// always check HTTP response code first
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
} else {
// extracts file name from URL
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
fileURL.length());
}
System.out.println("Content-Type = " + contentType);
System.out.println("Content-Disposition = " + disposition);
System.out.println("Content-Length = " + contentLength);
System.out.println("fileName = " + fileName);
// opens input stream from the HTTP connection
InputStream inputStream = httpConn.getInputStream();
String saveFilePath = saveDir + File.separator + fileName;
// opens an output stream to save into file
FileOutputStream outputStream = new FileOutputStream(saveDir);
int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("File downloaded");
} else {
System.out.println("No file to download. Server replied HTTP code: " + responseCode);
}
httpConn.disconnect();
}catch(Exception e){
e.printStackTrace();
}
return null;
}
protected void onProgressUpdate(String... progress) {
pDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String file_url) {
dismissDialog(progress_bar_type);
}
}
Although Volley library is not recommended for large download or streaming operations, however, I'd like to share my following working sample code.
Let's assume we download only MP3 files so I hard-code the extension. And of course, we should check more carefully to avoid exceptions (NullPointer...) such as checking whether headers contain "Content-Disposition" key or not...
Hope this helps!
Volley Custom class:
public class BaseVolleyRequest extends Request<NetworkResponse> {
private final Response.Listener<NetworkResponse> mListener;
private final Response.ErrorListener mErrorListener;
public BaseVolleyRequest(String url, Response.Listener<NetworkResponse> listener, Response.ErrorListener errorListener) {
super(0, url, errorListener);
this.mListener = listener;
this.mErrorListener = errorListener;
}
#Override
protected Response<NetworkResponse> parseNetworkResponse(NetworkResponse response) {
try {
return Response.success(
response,
HttpHeaderParser.parseCacheHeaders(response));
} catch (JsonSyntaxException e) {
return Response.error(new ParseError(e));
} catch (Exception e) {
return Response.error(new ParseError(e));
}
}
#Override
protected void deliverResponse(NetworkResponse response) {
mListener.onResponse(response);
}
#Override
protected VolleyError parseNetworkError(VolleyError volleyError) {
return super.parseNetworkError(volleyError);
}
#Override
public void deliverError(VolleyError error) {
mErrorListener.onErrorResponse(error);
}
}
Then in your Activity:
public class BinaryVolleyActivity extends AppCompatActivity {
private final Context mContext = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_binary_volley);
RequestQueue requestQueue = Volley.newRequestQueue(mContext);
String url = "http://www.youtubeinmp3.com/download/get/?i=3sI2yV5mJ0kQ8CnddqmANZqK8a%2BgVQJ%2Fmg3xwhHTUsJKuusOCZUzebuWW%2BJSFs0oz8VTs6ES3gjohKQMogixlQ%3D%3D";
BaseVolleyRequest volleyRequest = new BaseVolleyRequest(url, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
Map<String, String> headers = response.headers;
String contentDisposition = headers.get("Content-Disposition");
// String contentType = headers.get("Content-Type");
String[] temp = contentDisposition.split("filename=");
String fileName = temp[1].replace("\"", "") + ".mp3";
InputStream inputStream = new ByteArrayInputStream(response.data);
createLocalFile(inputStream, fileName);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", error.toString());
}
});
volleyRequest.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 10, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(volleyRequest);
}
private String createLocalFile(InputStream inputStream, String fileName) {
try {
String folderName = "MP3VOLLEY";
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, folderName);
folder.mkdir();
File file = new File(folder, fileName);
file.createNewFile();
FileOutputStream f = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
f.write(buffer, 0, length);
}
//f.flush();
f.close();
return file.getPath();
} catch (IOException e) {
return e.getMessage();
}
}
}
Here the result screenshot:
NOTE:
As I commented below, because the direct download Url changes regularly, you should check the new url with some tools such as Postman for Chrome, if it responses binary instead of a web page (expired url), then the Url is valid and my code works for that Url.
Refer to the two following screenshots:
Expired url:
Un-expired url:
UPDATE BASIC LOGIC FOR GETTING DIRECT DOWNLOAD LINK FROM THAT SITE'S DOCUMENTATION:
According to Create Your Own YouTube To MP3 Downloader For Free
You can take a look at
JSON Example
You can also receive the data in JSON by setting the "format"
parameter to "JSON".
http://YouTubeInMP3.com/fetch/?format=JSON&video=http://www.youtube.com/watch?v=i62Zjga8JOM
Firstly, you create a JsonObjectRequest getting response from the above file link. Then, inside onResponse of this JsonObjectRequest you will get the direct download link, like this directUrl = response.getString("link"); and use BaseVolleyRequest volleyRequest
I have just told the logic for getting direct url, IMO, you should implement it yourself. Goodluck!
Use below code it works fine for encrypted URLs
public class HttpDownloadUtility {
private static final int BUFFER_SIZE = 4096;
/**
* Downloads a file from a URL
* #param fileURL HTTP URL of the file to be downloaded
* #param saveDir path of the directory to save the file
* #throws IOException
*/
public static void downloadFile(String fileURL, String saveDir)
throws IOException {
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
// always check HTTP response code first
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
} else {
// extracts file name from URL
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
fileURL.length());
}
System.out.println("Content-Type = " + contentType);
System.out.println("Content-Disposition = " + disposition);
System.out.println("Content-Length = " + contentLength);
System.out.println("fileName = " + fileName);
// opens input stream from the HTTP connection
InputStream inputStream = httpConn.getInputStream();
String saveFilePath = saveDir + File.separator + fileName;
// opens an output stream to save into file
FileOutputStream outputStream = new FileOutputStream(saveFilePath);
int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("File downloaded");
} else {
System.out.println("No file to download. Server replied HTTP code: " + responseCode);
}
httpConn.disconnect();
}
}
The url returns a 302 redirect to the actual .mp3. The browser does the redirect in the background for you, but in your app you need to do it yourself. Here is an example on how to do that with HttpUrlConnection http://www.mkyong.com/java/java-httpurlconnection-follow-redirect-example/
If you know the type of file in advance then you can download your file from url which don't have extension.
DownloadService .java
public class DownloadService extends IntentService {
public static final int UPDATE_PROGRESS = 8344;
private Context context;
private PowerManager.WakeLock mWakeLock;
ProgressDialog mProgressDialog;
String filename;
File mypath;
String urlToDownload;
BroadcastReceiver broadcaster;
Intent intent1;
static final public String BROADCAST_ACTION = "com.example.app.activity.test.broadcast";
public DownloadService() {
super("DownloadService");
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
intent1 = new Intent(BROADCAST_ACTION);
}
#Override
protected void onHandleIntent(Intent intent) {
ResultReceiver receiver = (ResultReceiver) intent.getParcelableExtra("receiver");
try {
intent1 = new Intent(BROADCAST_ACTION);
urlToDownload = intent.getStringExtra("url");
filename= intent.getStringExtra("filename");
BufferedWriter out;
try {
File path=new File("/sdcard/","folder name");
path.mkdir();
mypath=new File(path,filename);
Log.e("mypath",""+mypath);
if (!mypath.exists()) {
out= new BufferedWriter(new FileWriter(mypath));
//ut = new OutputStreamWriter(context.openFileOutput( mypath.getAbsolutePath() ,Context.MODE_PRIVATE));
out.write("test");
out.close();
}
}catch(Exception e){
e.printStackTrace();
}
URL url = new URL(urlToDownload);
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a typical 0-100% progress bar
int fileLength = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(connection.getInputStream());
OutputStream output = new FileOutputStream(mypath);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
Bundle resultData = new Bundle();
resultData.putInt("progress" ,(int) (total * 100 / fileLength));
//Log.e("mypath",""+mypath);
resultData.putString("mypath", ""+mypath);
receiver.send(UPDATE_PROGRESS, resultData);
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
Bundle resultData = new Bundle();
resultData.putInt("progress" ,100);
resultData.putString("mypath", ""+mypath);
receiver.send(UPDATE_PROGRESS, resultData);
intent1.putExtra("progressbar", 100);
sendBroadcast(intent1);
}
}
DownloadReceiver.java
public class DownloadReceiver extends ResultReceiver{
private Context context;
private PowerManager.WakeLock mWakeLock;
ProgressDialog mProgressDialog;
String filename;
String mypath;
public DownloadReceiver(Handler handler ,String filename ,Context context) {
super(handler);
this.context = context;
this.filename = filename;
mProgressDialog = new ProgressDialog(context);
}
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
super.onReceiveResult(resultCode, resultData);
if (resultCode == DownloadService.UPDATE_PROGRESS) {
int progress = resultData.getInt("progress");
mypath = resultData.getString("mypath");
mProgressDialog.setProgress(progress);
//Log.e("progress","progress");
mProgressDialog.setMessage("App name");
mProgressDialog.setIndeterminate(true);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(true);
if (progress == 100) {
mProgressDialog.dismiss();
Log.e("download","download");
}
}
}
}
Now start service in your mainactivity by below code :
Intent miIntent = new Intent(mContext, DownloadService.class);
miIntent.putExtra("url", url);
miIntent.putExtra("filename", id+".mp3");
miIntent.putExtra("receiver", new DownloadReceiver(new Handler() , id,mContext));
startService(miIntent);

Fails to save file (image) in some devices

In my application I'll download an Image from a url and write it into an external storage. It works on 2 out of 3 devices I've tested and failed on 3rd. The first 2 are LG and Lenovo devices (unrooted) and the 3rd one is a Lenovo (rooted). Now when I save the file using below code everything works fine on first 2 devices but throws an:
IOException: open failed: EINVAL (Invalid argument)
while creating the file. I don't have any illegal character in my file name as it is shown below.
InputStream in = connection.getInputStream();
newPath = path + "/" + fileNameMobile;
File outFile = new File(newPath);
if(!outFile.exists()) {
outFile.createNewFile(); // fails here
}
OutputStream out = new FileOutputStream(outFile);
ImageHandler.copyFile(in, out);
out.flush();
out.close();
in.close();
and newPath is
/storage/sdcard0/com.rahil.ecat/_5577d1b953e54351a4a7132252c11304.jpg
I can't find exactly why it fails on 1 device and works on the other 2 devices. Anyone has any idea? Thanks in advance
EDIT: Here's how I get the fileNameMoblie:
String fileNameMobile = _url.substring(_url.lastIndexOf('/') + 1);
and get the path and pass it to function as below:
File sdCardRoot = Environment.getExternalStorageDirectory();
File yourDir = new File(sdCardRoot, _Context.getPackageName());
and here's the result of outFile.getAbsolutePath():
/storage/sdcard0/com.rahil.ecat/_5577d1b953e54351a4a7132252c11304.jpg
EDIT 2: Here's the complete code:
Class ImageTask
public class ImageTask extends AsyncTask<Void, String, Void> {
private Context _Context;
private String _token;
private ImageView _imageView;
private ProgressBar _pbar;
private String _url;
private HttpRequestHandler _hrh;
private ImageType _type;
private RoundedImageView _rImageView;
public ImageTask(Context context, String token, ImageView imageView, RoundedImageView rImageView, ImageType type) {
this._Context = context;
_token = token;
_imageView = imageView;
_type = type;
_rImageView = rImageView;
}
#Override
protected Void doInBackground(Void... voids) {
if(!_token.isEmpty())
{
File sdCardRoot = Environment.getExternalStorageDirectory();
File yourDir = new File(sdCardRoot, _Context.getPackageName());
boolean found = false;
String[] tokenParts = _token.split("\\.");
String realToken = _token;
if(tokenParts.length == 2)
{
realToken = tokenParts[0];
}
for (File f : yourDir.listFiles()) {
if (f.isFile()) {
String name = f.getName();
if(name.contains(realToken))
{
found = true;
if(Util.isMobile(name))
{
publishProgress(yourDir.getPath() + '/' + name, "NULL");
}
else
{
if(Util.hasActiveInternetConnection(_Context)) {
getUrl();
if(!_url.isEmpty()) {
_hrh = new HttpRequestHandler(_url, _Context);
String fileName = _hrh.downloadImage(yourDir.getPath(), _token, true);
if (!fileName.isEmpty()) {
if(fileName.contains("-mob")) {
f.delete();
}
publishProgress(fileName, "NULL");
} else {
publishProgress("", "DEFAULT");
}
}else {
publishProgress("", "DEFAULT");
}
}
else
{
publishProgress("", "DEFAULT");
}
}
}
}
}
if(!found)
{
if(Util.hasActiveInternetConnection(_Context))
{
getUrl();
if(!_url.isEmpty()) {
_hrh = new HttpRequestHandler(_url, _Context);
String fileName = _hrh.downloadImage(yourDir.getPath(), _token, false);
if (!fileName.isEmpty()) {
publishProgress(fileName, "NULL");
} else {
publishProgress("", "DEFAULT");
}
}else {
publishProgress("", "DEFAULT");
}
}
else
{
publishProgress("", "DEFAULT");
}
}
}
else
{
loadDefaultImage();
}
return null;
}
#Override
protected void onProgressUpdate(String... values) {
if(values[1].equals("DEFAULT"))
{
loadDefaultImage();
}
else
{
loadImage(values[0]);
}
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void loadImage(String path)
{
try {
Bitmap image = BitmapFactory.decodeFile(path);
if (image != null) {
if(_imageView != null) {
StreamDrawable sd = null;
if(_type == ImageType.BLUR)
{
sd = new StreamDrawable(image, 10, 10);
_imageView.setBackground(sd);
}
else if(_type == ImageType.NO_EFFECT)
{
_imageView.setImageBitmap(image);
}
}
else if(_rImageView != null) {
_rImageView.setImageBitmap(image);
}
}
}
catch(Exception ex)
{
loadDefaultImage();
}
}
private void getUrl()
{
WebService ws = new WebService(_Context);
_url = ws.getImageUrlForScreenTypeAndToken(
_token,
Util.getScreenType(_Context).name());
}
private void loadDefaultImage()
{
if(_imageView != null) {
_imageView.setBackgroundResource(R.drawable.noimage);
}
else if(_rImageView != null) {
_rImageView.setBackgroundResource(R.drawable.noimage);
}
}
}
Class HttpRequestHandler
public class HttpRequestHandler {
private String _url;
private Context _Context;
private ProgressDialog _dialog;
public HttpRequestHandler(String url, Context context) {
_url = url;
_Context = context;
}
public String init_post(List<NameValuePair> nameValuePairs) {
String data = null ;
BufferedReader in = null;
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpConnectionParams.setConnectionTimeout(params, 10000);
HttpConnectionParams.setSoTimeout(params, 5000);
HttpClient httpclient = new DefaultHttpClient(params);
HttpPost httppost = new HttpPost(_url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse response = httpclient.execute(httppost);
data = parser(response.getEntity());
} catch (Exception e) {
}
return data;
}
public String init() {
String data = null ;
BufferedReader in = null;
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpConnectionParams.setConnectionTimeout(params, 10000);
HttpConnectionParams.setSoTimeout(params, 5000);
HttpClient httpclient = new DefaultHttpClient(params);
HttpGet request = new HttpGet();
URI website = new URI(_url);
request.setURI(website);
HttpResponse response = httpclient.execute(request);
data = parser(response.getEntity());
} catch (Exception t) {
if(true)
{
String s = "asd";
}
}
return data;
}
private String parser(HttpEntity entity){
InputStream is = null;
String jsonParse = "";
try {
is = entity.getContent();
//BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
jsonParse = sb.toString();
} catch (IOException e) {
e.printStackTrace();
}
return jsonParse;
}
public String downloadImage(String path, String token, boolean check) {
String newPath = "";
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
String fileNameMobile = _url.substring(_url.lastIndexOf('/') + 1);
if(check && token.equals(fileNameMobile))
{
return newPath;
}
URL urlConnection = new URL(_url);
URLConnection connection = urlConnection.openConnection();
InputStream in = connection.getInputStream();
newPath = path + "/" + fileNameMobile;
File outFile = new File(newPath);
OutputStream out = new FileOutputStream(outFile);
ImageHandler.copyFile(in, out);
out.flush();
out.close();
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return newPath;
}
}
This permission.
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
This code.
InputStream in = connection.getInputStream();
String filepath = getFilesDir().toString() + "/MyCustomFolder/";
File imagesFolder = new File(filepath);
if(!imagesFolder.exists())
imagesFolder.mkdirs();
File outFile = new File(filepath + "FileName.jpg");
if(!outFile.exists()){
OutputStream out = new FileOutputStream(outFile);
ImageHandler.copyFile(in, out);
out.flush();
out.close();
in.close();
}else{
in.close();
}

Converting a J2ME URLCaller Class to Android equivalent

I got a Class from a friend for a URlCaller class for connecting to a webservice. My assumption was that all will work well, but it contains error below is the J2ME implementation
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package main;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
public class URLCaller extends Thread{
private String url ;
private String action;
private URLEncoder urle;
private String res;
public URLCaller() {
}
public URLCaller(String action,String url) {
urle = new URLEncoder();
this.url = url;
this.action = action;
start();
}
//replace
void authenticate(String action,String url) {
HttpConnection connection = null;
InputStream is = null;
OutputStream os = null;
StringBuffer stringBuffer = new StringBuffer();
try {
connection = (HttpConnection)Connector.open(url);
connection.setRequestMethod(HttpConnection.GET);
connection.setRequestProperty("IF-Modified-Since","20 Jan 2001 16:19:14 GMT");
connection.setRequestProperty("User-Agent","Profile/MIDP-2.0 Confirguration/CLDC-1.0");
connection.setRequestProperty("Content-Language", "en-CA");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
os = connection.openOutputStream();
is = connection.openDataInputStream();
int ch;
while ((ch = is.read()) != -1) {
stringBuffer.append((char) ch);
}
res = stringBuffer.toString() ;
System.out.println(res);
//textBox = new TextBox("Simple GET Test", stringBuffer.toString(), 1024, 0);
}
catch(Exception e ){
}
finally {
try{
if(is!= null) {
is.close();
}
if(os != null) {
os.close();
}
if(connection != null) {
connection.close();
}
//display.setCurrent(textBox);
}
catch(Exception e ){
}
}
}
void sendSMS(String action,String url) {
HttpConnection connection = null;
InputStream is = null;
OutputStream os = null;
StringBuffer stringBuffer = new StringBuffer();
//TextBox textBox = null;
try {
connection = (HttpConnection)Connector.open(url);
connection.setRequestMethod(HttpConnection.GET);
connection.setRequestProperty("IF-Modified-Since","20 Jan 2001 16:19:14 GMT");
connection.setRequestProperty("User-Agent","Profile/MIDP-2.0 Confirguration/CLDC-1.0");
connection.setRequestProperty("Content-Language", "en-CA");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
os = connection.openOutputStream();
is = connection.openDataInputStream();
int ch;
while ((ch = is.read()) != -1) {
stringBuffer.append((char) ch);
}
res = stringBuffer.toString() ;
System.out.println(res);
//textBox = new TextBox("Simple GET Test", stringBuffer.toString(), 1024, 0);
}
catch(Exception e ){
}
finally {
try{
if(is!= null) {
is.close();
}
if(os != null) {
os.close();
}
if(connection != null) {
connection.close();
}
//display.setCurrent(textBox);
}
catch(Exception e ){
}
}
}
public void run(){
//http://message url?user=mu&password=my&from=Muyiwa&to=23475061254040&message=i+love+this.
System.out.println(Thread.currentThread().toString() + " is running...") ;
if (action.equals("login")){
System.out.println(action);
authenticate(action,url);
}
else if(action.equals("sendsms")) {
System.out.println(action);
sendSMS(action,url);
}
}
public void callURL(){
HttpConnection c = null;
InputStream is = null;
StringBuffer sb = new StringBuffer();
try{
System.out.println(url);
//url = (urle.encode(url,"UTF-8"));
//System.out.println(url);
c = (HttpConnection)Connector.open(url, Connector.READ_WRITE, true);
c.setRequestMethod(HttpConnection.POST); //default
is = c.openInputStream(); // transition to connected!
int ch = 0;
for(int ccnt=0; ccnt < 150; ccnt++) { // get the title.
ch = is.read();
if (ch == -1){
break;
}
sb.append((char)ch);
}
res = sb.toString();
}catch(Exception e){
e.printStackTrace();
}
}
public String getRes() {
return res;
}
public void setRes(String res) {
this.res = res;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public URLEncoder getUrle() {
return urle;
}
public void setUrle(URLEncoder urle) {
this.urle = urle;
}
}
Ps could someone convert this to an android implementation. Currently facing a deadline
In android there are classes, HttpClient and DefaultHttpClient. So you make a web request using these.
Same as your code make a HttpGet request, And also in Like your J2ME code, instead of Thread class you can use AsyncTask (You can also use Thread, Handler but Asynctask is better to use) to perform a web request in Non-UI thread.
Example:
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
textView.setText(result);
}
}
Now from your Android activity code you have to just execute() this DownloadWebPageTask.
Like,
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { url });
For more information look at this Tutorial

Categories

Resources