URL url = new URL(path);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH = "/mnt/sdcard/Android/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "version.txt");
if(outputFile.exists()){
outputFile.delete();
}
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
Exception caught: java.io.FileNotFoundException http://192.168.2.143/version.txt, where path="http://192.168.2.143/version.txt", I use browser in my device to open http://192.168.2.143/version.txt, can be opened. I have INTERNET permission in my manifest. Any idea?
It's the same problem I was having:
HttpUrlConnection returns FileNotFoundException if you try to read the getInputStream() from the connection.
You should instead use getErrorStream() when the status code is higher than 400.
More than this, please be careful since it's not only 200 to be the success status code, even 201, 204, etc. are often used as success statuses.
Here is an example of how I went to manage it
... connection code code code ...
// Get the response code
int statusCode = connection.getResponseCode();
InputStream is = null;
if (statusCode >= 200 && statusCode < 400) {
// Create an InputStream in order to extract the response object
is = connection.getInputStream();
}
else {
is = connection.getErrorStream();
}
... callback/response to your handler....
In this way, you'll be able to get the needed response in both success and error cases.
Hope this helps!
Try this to read file over the internet: Reading Text File From Server on Android
I'm not sure you can use File.
Related
I am downloading HTML file from server using URLConnection but I am getting FileNotFoundException. My path is correct. Using same code same file is downloaded on android of API level 25 but on API level less than it is not downloading. Also connection.getContentLength(); is giving 311 value always. I am not getting any answer to solve this. I am hereby adding my code.
My class file code is
String HomeScreenResourcefilename = WebHomescreenResObj.getString("FileName");
int ProductTargetID = WebHomescreenResObj.getInt("ProductTargetID");
String WebURL_Part1 = context.getResources().getString(R.string.FileDownloadRootPath)+"/ExhibitorData/";
String WebURL_Part2 = GlobalVariables.tradeShowName+" - "+GlobalVariables.exhibitorName+"/HTMLHomeScreen/"+ProductTargetID +"/"+HomeScreenResourcefilename;
String WebURL = WebURL_Part1 + WebURL_Part2;
try {
URL url = new URL(WebURL);
File file = new File(context.getFilesDir(), HomeScreenResourcefilename);
URLConnection connection = url.openConnection();
connection.connect();
FileOutputStream fileOutput = new FileOutputStream(file);
//Stream used for reading the data from the internet
InputStream inputStream = connection.getInputStream();
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
} catch (Exception e1) {
e1.printStackTrace();
LogE("error in 14 :"+e1);
}
Use HttpURLConnection and then connection.getResponseCode() to get the status code. If it is greater than 400, that might be the reason.
Update: Use url encoding.
I have a published Android application that has an HTTP audio download process.
This processed worked fine until today.
whats wrong with my code?
final URL downloadFileUrl = new URL(mPerformanceSong.getPreviewUrl());
final HttpURLConnection httpURLConnection = (HttpURLConnection) downloadFileUrl.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setDoOutput(true);
httpURLConnection.setConnectTimeout(10000);
httpURLConnection.setReadTimeout(10000);
httpURLConnection.connect();
mTrackDownloadFile = new File(RecordPerformance.this.getCacheDir(), "mediafile");
mTrackDownloadFile.createNewFile();
final FileOutputStream fileOutputStream = new FileOutputStream(mTrackDownloadFile);
final byte buffer[] = new byte[16 * 1024];
final InputStream inputStream = httpURLConnection.getInputStream();
int len1 = 0;
while ((len1 = inputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer, 0, len1);
}
fileOutputStream.flush();
fileOutputStream.close();
The content of the downloaded file appears to be gzip.
does this mean i need to wrap my inputStream in GZIPInputStream?
an example download URL is
http://www.amazon.com/gp/dmusic/get_sample_url.html?ASIN=B008TMSNMI
I'm actually surprised it's downloading anything - are you sure it is?
The http url that you've posted:
http://www.amazon.com/gp/dmusic/get_sample_url.html?ASIN=B008TMSNMI
Is currently redirecting to an https cloudfront address:
https://d28julafmv4ekl.cloudfront.net/...
HttpUrlConnection will not follow redirects across schemes (ie from http to https).
So if you change your *.amazon.com URLs to https, perhaps it would fix your issue...
I have an app to download zip file content from drop box (which is publicly shared path). i wrote download code using HttpURLConnection but its not working as intended and instead is downloading a small portion (after download zip file showing 31 kb but its original size is 3mb). i am attching my code. please help me to solve this.
URL url = new URL("drop box public share url");
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setAllowUserInteraction(false);
urlConnection.setInstanceFollowRedirects(true);
urlConnection.setConnectTimeout(5 * 1000);
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
File SDCardRoot = Environment.getExternalStorageDirectory();
File file = new File(SDCardRoot,"/download/sample.zip");
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength();
int downloadedSize = 0;
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
onProgressUpdate(downloadedSize, totalSize);
}
//close the output stream when done
fileOutput.close();
inputStream.close();
It seems that the method call:
setDoOuput(true);
makes the request a POST (see
What exactly does URLConnection.setDoOutput() affect?)
Removing it seems to fix the issue.
Try to use plain URLConnection not HttpURLConnection. And see the output.
i am using below code to downloading file from URL.
URL url = new URL(mCoreContent.VideoURI);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
lenghtOfFile = c.getContentLength();
InputStream input = c.getInputStream();
BufferedInputStream bis = new BufferedInputStream(input);
ByteArrayOutputStream output = new ByteArrayOutputStream((int) lenghtOfFile);
int buffer = 4096;
byte data[] = new byte[buffer];
int current = 0;
while ((current = bis.read(data, 0, buffer)) != -1) {
output.write(data, 0, current);
}
i tested above code with two different device. one device taking less than a minute downloading the file and another takes more than 5-10 to downloading same with same network connecting. i tested multiple times and i am getting the same result. Please help.
Thanks in advance.
how can i download audio file from server by url and save it to sdcard.
i am using the code below:
public void uploadPithyFromServer(String imageURL, String fileName) {
try {
URL url = new URL(GlobalConfig.AppUrl + imageURL);
File file = new File(fileName);
Log.d("ImageManager", "download begining");
Log.d("ImageManager", "download url:" + url);
Log.d("ImageManager", "downloaded file name:" + fileName);
/* Open a connection to that URL. */
URLConnection con = url.openConnection();
InputStream is = con.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is, 1024 * 50);
FileOutputStream fos = new FileOutputStream("/sdcard/" + file);
byte[] buffer = new byte[1024 * 50];
int current = 0;
while ((current = bis.read(buffer)) != -1) {
fos.write(buffer, 0, current);
}
fos.flush();
fos.close();
bis.close();
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
}
the above code is not downloading audio file.
if use any permission in menifest file plz tell me.. (i have used internet permission)
please help
thanks..
you must also add
android.permission.WRITE_EXTERNAL_STORAGE
permission if you wish to write data to sd card.
also post your logcat output , if you are getting any IOExceptions.
Your example does not specify a request method and some mimetypes and stuff.
Here you will find a list of mimetypes http://www.webmaster-toolkit.com/mime-types.shtml
Find the mimetypes relevant to you and add it to the mimetypes specified below in the code.
Oh and btw, the below is normal Java code. You'll have to replace the bit that stores the file on the sdcard. dont have an emulator or phone to test that part at the moment
Also see the docs for storage permissions on sd here: http://developer.android.com/reference/android/Manifest.permission_group.html#STORAGE
public static void downloadFile(String hostUrl, String filename)
{
try {
File file = new File(filename);
URL server = new URL(hostUrl + file.getName());
HttpURLConnection connection = (HttpURLConnection)server.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.addRequestProperty("Accept","image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/x-shockwave-flash, */*");
connection.addRequestProperty("Accept-Language", "en-us,zh-cn;q=0.5");
connection.addRequestProperty("Accept-Encoding", "gzip, deflate");
connection.connect();
InputStream is = connection.getInputStream();
OutputStream os = new FileOutputStream("c:/temp/" + file.getName());
byte[] buffer = new byte[1024];
int byteReaded = is.read(buffer);
while(byteReaded != -1)
{
os.write(buffer,0,byteReaded);
byteReaded = is.read(buffer);
}
os.close();
} catch (IOException e) {
e.printStackTrace();
}
Then call,
downloadFile("http://localhost/images/bullets/", "bullet_green.gif" );
EDIT:
Bad coder me.
Wrap that input InputStream in a BufferedInputStream. No need to specify buffersizes ect.
Defaults are good.