Download With In Android - java

I'm a beginner with android programming.
I'm having some problem with downloading a file with android
I used Httpost, Httpget and hhtpurlconnection
the two first aren't working at all
and the the third can't download tow times
I want a way to download different xmls to string or inputstream (or something convertable to them) to parse those XMLs.
besides the method should be able to do something like this :
conn.setRequestProperty("Authorization", "Basic " + encodedStr);
because the xmls are responses from an API

Here I am putting an example how to download an image file from server. I am asuming that on your local server there is a picture folder and you are downloading pic from that..
Use following code it may help you..
public class DownloadType1 extends Activity{
String dwnload_file_path = "http://10.0.2.2/pictures/webicon.PNG";
String dest_file_path = Environment.getRootDirectory()+"/pictures/img1.png";
ProgressDialog dialog = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.download1);
}
public void onClick(View v) {
dialog = ProgressDialog.show(DownloadType1.this, "", "Downloading file...", true);
new Thread(new Runnable() {
public void run() {
downloadFile(dwnload_file_path, dest_file_path);
}
}).start();
}
public void downloadFile(String url, String dest_file_path) {
try {
File dest_file = new File(dest_file_path);
URL u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(dest_file));
fos.write(buffer);
fos.flush();
fos.close();
hideProgressIndicator();
} catch(FileNotFoundException e) {
hideProgressIndicator();
return;
} catch (IOException e) {
hideProgressIndicator();
return;
}
}
void hideProgressIndicator(){
runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
}
});
}
}

Below an example that you can use to download a file. Naturally you will have to use a correct URL.
public InputStream downloadXmlFileStreamUsingUrl(final String url) {
log.info(String.format("downloadXmlFileStreamUsingUrl: %s", url));
final HttpGet getRequest = new HttpGet(url);
HttpClient client;
try {
client = new DefaultHttpClient();
final HttpResponse getResponse = client.execute(getRequest);
final int statusCode = getResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
log.warn("Error " + statusCode + " for URL " + url);
return null;
}
final HttpEntity getResponseEntity = getResponse.getEntity();
final InputStream content = getResponseEntity.getContent();
return content;
} catch (final IOException e) {
getRequest.abort();
log.warn("Exception in downloadXmlFileStreamUsingUrl, error for URL " + url + e, e);
}
finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
client.getConnectionManager().shutdown();
}
return null;
}

Related

Trouble downloading photos

I wrote a program that
Download the photo from the url...
But I have a problem...
Some photos are downloaded.
And there is no problem.
But some of the pictures are not downloadable incompletely :(
and in the file manager I look at
it is broken
Can you help?
my code is:
public class DownloadFileFromURL_img extends AsyncTask {
private viewHolderPost holderPOST;
public DownloadFileFromURL_img(viewHolderPost holderPOST) {
Log.d(TAG, "DownloadFileFromURL_img: ");
this.holderPOST = holderPOST;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
/**
* Downloading file in background thread
*/
#Override
protected String doInBackground(String... f_url) {
int count;
try {
File file = new File(Environment.getExternalStorageDirectory(), "98Diha/img");
if (!file.exists()) {
if (!file.mkdirs()) {
file.createNewFile();
}
}
InputStream input = null;
int response = -1;
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
if (!(conection instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conection;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
input = httpConn.getInputStream();
}
}
catch (Exception ex)
{
throw new IOException("Error connecting");
}
int lenghtOfFile = conection.getContentLength();
input = new BufferedInputStream(url.openStream());
String imgS[] = f_url[0].split("/");
String name = imgS[imgS.length - 1];
String path = Environment
.getExternalStorageDirectory().toString()
+ "/98diha/img/" + name;
File filePath = new File(path);
if (!filePath.exists()) {
OutputStream output = new FileOutputStream(path);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} else {
SSToast(context, "Exist!");
holderPOST.dowload_img.setVisibility(View.GONE);
holderPOST.setWallpaper.setVisibility(View.VISIBLE);
holderPOST.setWallpaper.setText(context.getString(R.string.set_wp));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
holderPOST.setWallpaper.setTextColor(ContextCompat.getColor(context, R.color.Teal_400));
} else {
holderPOST.setWallpaper.setTextColor(context.getResources().getColor(R.color.Teal_400));
}
}
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* Updating progress bar
*/
protected void onProgressUpdate(String... progress) {
holderPOST.dowload_img.setVisibility(View.GONE);
holderPOST.setWallpaper.setVisibility(View.VISIBLE);
holderPOST.setWallpaper.setText(context.getString(R.string.dowloading));
}
/**
* After completing background task Dismiss the progress dialog
**/
#Override
protected void onPostExecute(String file_url) {
holderPOST.setWallpaper.setText(context.getString(R.string.set_wp));
holderPOST.setWallpaper.setTextColor(context.getResources().getColor(R.color.Teal_400));
Log.d(TAG, "onPostExecute: ");
}
}
Instead of using AsyncTask to download images from URL. You can use libraries such as Glide or Picasso to do it quickly just in one line. But if you don't want to use libraries than you could use DownloadManager to download it and save it in a file. You can check this tutorial or other tutorials on the web for the implementation of DownloadManager.

Java: Can't convert string to array

I can't convert a string to an array!
String text = "";
String[] textsplit = {};
//Stuff
The app set the content of an online txt file in a string:
The online txt file contain: hello,my,name,is,simone
[...] //Downloading code
text = bo.toString(); //Set the content of the online file to the string
Now the string text is like this:
text = "hello,my,name,is,simone"
Now i have to convert the string to an array that must be like this:
textsplit = {"hello","my","name","is","simone"}
so the code that i use is:
textsplit = text.split(",");
But when i try to use the array the app crash! :(
For example:
textview.setText(textsplit[0]); //The text of the textview is empity
textview.setText(textsplit[1]); //The app crash
textview.setText(textsplit[2]); //The app crash
etc...
where am I wrong? thanks!
EDIT: This is the code:
new Thread() {
#Override
public void run() {
String path ="http://www.luconisimone.altervista.org/ciao.txt";
URL u = null;
try {
u = new URL(path);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.connect();
InputStream in = c.getInputStream();
final ByteArrayOutputStream bo = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
in.read(buffer); // Read from Buffer.
bo.write(buffer); // Write Into Buffer.
runOnUiThread(new Runnable() {
#Override
public void run() {
text = bo.toString();
testo.setText("(" + text + ")");
try {
bo.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
// Here all variables became empity
textsplit = text.split(",");
datisplittati.setText(textsplit[0]);
Try :
String text = "hello,my,name,is,simone";
String[] textArr = text.split(Pattern.quote(","));
You can get string using AsyncTask
private class GetStringFromUrl extends AsyncTask<String, Void, String> {
ProgressDialog dialog ;
#Override
protected void onPreExecute() {
super.onPreExecute();
// show progress dialog when downloading
dialog = ProgressDialog.show(MainActivity.this, null, "Downloading...");
}
#Override
protected String doInBackground(String... params) {
// #BadSkillz codes with same changes
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(params[0]);
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(entity);
InputStream is = buf.getContent();
BufferedReader r = new BufferedReader(new InputStreamReader(is));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line + "\n");
}
String result = total.toString();
Log.i("Get URL", "Downloaded string: " + result);
return result;
} catch (Exception e) {
Log.e("Get Url", "Error in downloading: " + e.toString());
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// TODO change text view id for yourself
TextView textView = (TextView) findViewById(R.id.textView1);
// show result in textView
if (result == null) {
textView.setText("Error in downloading. Please try again.");
} else {
textView.setText(result);
}
// close progresses dialog
dialog.dismiss();
}
}
and use blow line every time that you want:
new GetStringFromUrl().execute("http://www.luconisimone.altervista.org/ciao.txt");
You're using new thread to get data from an url. So in runtime, data will be asynchronous.
So when you access text variable (split it), it's still not get full value (example reason: network delay).
Try to move the function split after text = bo.toString(); , I think it will work well.

Downloading files from Zippyshare in android

I want to download files from Zippyshare site in Android.
The problem is that content length returned is -1. So I am not able to download a valid file.
Here is my code
public class DownloadFileDemo1 extends Activity {
ProgressBar pb;
Dialog dialog;
int downloadedSize = 0;
int totalSize = 0;
TextView cur_val;
String dwnload_file_path = "http://www17.zippyshare.com/i/95748527/55444/image.jpeg";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
showProgress(dwnload_file_path);
new Thread(new Runnable() {
public void run() {
downloadFile();
}
}).start();
}
void downloadFile(){
try {
URL url = new URL(dwnload_file_path);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Accept-Encoding", "gzip");
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//connect
urlConnection.connect();
//set the path where we want to save the file
File SDCardRoot = Environment.getExternalStorageDirectory();
//create a new file, to save the downloaded file
File file = new File(SDCardRoot,"downloaded_file.png");
FileOutputStream fileOutput = new FileOutputStream(file);
//Stream used for reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
System.out.println("ENCODING"+urlConnection.getContentEncoding());
if ("gzip".equals(urlConnection.getContentEncoding())) {
inputStream = new GZIPInputStream(inputStream);
}
InputSource is = new InputSource(inputStream);
//this is the total size of the file which we are downloading
totalSize = urlConnection.getContentLength();
runOnUiThread(new Runnable() {
public void run() {
pb.setMax(totalSize);
}
});
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
// update the progressbar //
runOnUiThread(new Runnable() {
public void run() {
pb.setProgress(downloadedSize);
float per = ((float)downloadedSize/totalSize) * 100;
cur_val.setText("Downloaded " + downloadedSize + "KB / " + totalSize + "KB (" + (int)per + "%)" );
}
});
}
//close the output stream when complete //
fileOutput.close();
runOnUiThread(new Runnable() {
public void run() {
// pb.dismiss(); // if you want close it..
}
});
} catch (final MalformedURLException e) {
showError("Error : MalformedURLException " + e);
e.printStackTrace();
} catch (final IOException e) {
showError("Error : IOException " + e);
e.printStackTrace();
}
catch (final Exception e) {
showError("Error : Please check your internet connection " + e);
}
}
void showError(final String err){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(DownloadFileDemo1.this, err, Toast.LENGTH_LONG).show();
}
});
}
void showProgress(String file_path){
dialog = new Dialog(DownloadFileDemo1.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.myprogressdialog);
dialog.setTitle("Download Progress");
TextView text = (TextView) dialog.findViewById(R.id.tv1);
text.setText("Downloading file from ... " + file_path);
cur_val = (TextView) dialog.findViewById(R.id.cur_pg_tv);
cur_val.setText("Starting download...");
dialog.show();
pb = (ProgressBar)dialog.findViewById(R.id.progress_bar);
pb.setProgress(0);
pb.setProgressDrawable(getResources().getDrawable(R.drawable.green_progress));
}
}
How can I solve this problem?
According to documentation of getContentLength:
Returns the content length in bytes specified by the response header
field content-length or -1 if this field is not set or cannot be
represented as an int.
If you will check your link here, then you will spot, that Content Length was not set.
(I will just add, that I was not checking fully your code, but generally in main downloading loop with buffer - is downloading something, but I was not checking if it was correct, or not)
EDIT: I'm gonna 'hate' guy, that gave me '-1'. I'm helping with detail link and how checking it, why content length is returning -1, and someone is giving me negative. I change little downloadFile function just to download file, without giving update to UI, and then we have:
void downloadFile(){
try {
URL url = new URL(dwnload_file_path);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Accept-Encoding", "gzip");
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//connect
urlConnection.connect();
//set the path where we want to save the file
//create a new file, to save the downloaded file
File file = new File("downloaded_file.png");
FileOutputStream fileOutput = new FileOutputStream(file);
//Stream used for reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
System.out.println("ENCODING"+urlConnection.getContentEncoding());
if ("gzip".equals(urlConnection.getContentEncoding())) {
inputStream = new GZIPInputStream(inputStream);
}
InputSource is = new InputSource(inputStream);
//this is the total size of the file which we are downloading
totalSize = urlConnection.getContentLength();
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
// update the progressbar //
}
//close the output stream when complete //
fileOutput.close();
} catch (final MalformedURLException e) {
e.printStackTrace();
} catch (final IOException e) {
e.printStackTrace();
}
catch (final Exception e) {
e.printStackTrace();
}
}
As I checked this code is downloading file, but it isn't this image, but html page from zippyshare, as zippy has kind of protection to download files from their site.

how to consume json web service deployed in iis in android

i have created restfull webservices (retun json data) in asp.net and deploye it on iis.now i want to consume that webServices in android..but in android its work fine in emulator but on android device its give error...
Error: Connection to" //http://ipAddress.:6547/" refused
plz help
thats code
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.recent_jsonws_map_layout);
}
public String readJSONFeed(String URL)
{
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try
{
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200)
{
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null)
{
stringBuilder.append(line);
}
inputStream.close();
}
else
{
Log.d("JSON", "Failed to download file");
}
}
catch (Exception e)
{
Log.e("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
#SuppressWarnings("unused")
private class ReadWeatherJSONFeedTask extends AsyncTask<String, Void, String>
{
protected String doInBackground(String... urls)
{
return readJSONFeed(urls[0]);
}
protected void onPostExecute(String result)
{
try
{
jsonObject = new JSONObject(result);
jsonArrayGeoPoint = new JSONArray(jsonObject.getString("jsondataResult").toString());
Toast.makeText(getApplicationContext(), jsonArrayGeoPoint.getString(0).toString()+"||"+jsonArrayGeoPoint.getString(1).toString(), Toast.LENGTH_SHORT).show();
String[] strArrtemp=new String[5];
Double[] strArrLat = new Double[5];
Double[] strArrLon = new Double[5];
for(int i=0; i<jsonArrayGeoPoint.length(); i++)
{
try
{
strArrtemp[i]=jsonArrayGeoPoint.getString(i).toString();
}
catch (JSONException e)
{
Log.e("JsonArray ERROR",e.getLocalizedMessage());
}
}
String[] arrytemp = new String[2];
String temp;
for(int i=0; i<strArrtemp.length; i++)
{
temp = strArrtemp[i].toString();
strArrLat[i]=Double.parseDouble(temp.substring(0,6));
strArrLon[i]=Double.parseDouble(temp.substring(7,13));
}
Toast.makeText(getApplicationContext(), "Lat1="+strArrLat[1].toString()+" & Lon1="+strArrLon.toString(), Toast.LENGTH_SHORT).show();
Button getDir;
getDir = (Button)findViewById(R.id.getLocationBtn);
getDir.setText(strArrLat[1].toString());
}
catch (Exception e)
{
Log.e("ReadWeatherJSONFeedTask", e.getLocalizedMessage());
}
}
}
enter code here
public void btnGetWeather(View view)
{ newReadWeatherJSONFeedTask().execute(http://ipAddress.:6547/RestServiceImpl.svc/jsondata/");
}
}
instead of using localhost use 10.0.2.2:portnumber

How to convert video file(.mp4) format into binary format in android?

I want to upload a video in web server. I got the service which to i want to pass a file in binary format how can i do this ?
I have tried to convert the video file into binary format with the help of base64..?
public class binaryformat extends Activity {
private String strAttachmentCoded;
Button b1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b1=(Button)findViewById(R.id.button1);
b1.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
File file = new File("/mnt/sdcard/C:/Program Files (x86)/Wowza Media Systems/Wowza Media Server 3.1.2/content/sample.mp4");
FileInputStream objFileIS = null;
try
{
objFileIS = new FileInputStream(file);
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
ByteArrayOutputStream objByteArrayOS = new ByteArrayOutputStream();
byte[] byteBufferString = new byte[1024];
try
{
for (int readNum; (readNum = objFileIS.read(byteBufferString)) != -1;)
{
objByteArrayOS.write(byteBufferString, 0, readNum);
System.out.println("read " + readNum + " bytes,");
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] byteBinaryData = Base64.encode((objByteArrayOS.toByteArray()), Base64.DEFAULT);
strAttachmentCoded = new String(byteBinaryData);
}
});
}
}
I have experienced in my 3 application that it is good if use XML to send the IMAGE or VIDEO over server.
Sending IMAGE or VIDEO in the form of base64 String in the XML is best if you want to upload a IMAGE or VIDEO in ANDROID.
public static String uploadMultiplePhoto(String url, String xmlString) {
String responseString = "";
try {
//instantiates httpclient to make request
DefaultHttpClient httpclient = new DefaultHttpClient();
//url with the post data
HttpPost request = new HttpPost(url);
//convert parameters into JSON object
//JSONObject holder = new JSONObject(jsonObjString);
//passes the results to a string builder/entity
StringEntity se = new StringEntity(xmlString);
//sets the post request as the resulting string
request.setEntity(se);
//sets a request header so the page receving the request
//will know what to do with it
request.setHeader("Accept", "application/xml");
/*request.setHeader("Content-type", "application/xml");*/
//Handles what is returned from the page
ResponseHandler<String> responseHandler = new BasicResponseHandler();
responseString = httpclient.execute(request, responseHandler);
} catch (Exception exception) {
exception.printStackTrace();
}
return responseString;
}

Categories