I'm trying to get a image from particular URL but it throwsFileNotFoundException. If I try to open the url from my browser, i can see the images. Please help. Below is my code. Thanks.
String fileURL = "http://sposter.smartag.my/images/KFC_Voucher.jpg";
String FILENAME = "caldophilus.jpg";
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
File root = Environment.getExternalStorageDirectory();
FileOutputStream f = new FileOutputStream(new File(root, FILENAME));
InputStream x=c.getInputStream();
int size=x.available();
byte b[]= new byte[size];
x.read(b);
f.write(b);
f.flush();
f.close();
i try this and its work fine. Thanks.
URL url = new URL(fileURL);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/caldophilus.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
Try this:
BufferedInputStream inputStream = null;
OutputStream out = null;
String fileName = null;
String path = null;
File savedFile = null;
try
{
// Replace your URL here.
URL fileURL = new URL("http://enter.your.url.here");
URLConnection connection = fileURL.openConnection();
connection.connect();
inputStream = new java.io.BufferedInputStream(connection.getInputStream());
// Replace your save path here.
File fileDir = new File("path/to/save");
fileDir.mkdirs();
savedFile = new File("path/to/save", fileName);
out = new FileOutputStream(savedFile);
byte buf[] = new byte[1024];
int len;
long total = 0;
while ((len = inputStream.read(buf)) != -1)
{
total += len;
out.write(buf, 0, len);
}
out.close();
inputStream.close();
}
catch (Exception)
{
}
Try the below code. It should work!
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
public class DownloadManager {
public static void downLoadImage(String imageURL, String destinationFileName) throws IOException {
URL url = new URL(imageURL);
InputStream inputStream = url.openStream();
OutputStream outputStream = new FileOutputStream(destinationFileName);
byte[] byteData = new byte[2048];
int length;
while((length=inputStream.read(byteData))!=-1) {
outputStream.write(byteData, 0, length);
}
inputStream.close();
outputStream.close();
}
public static void main(String[] args) throws IOException {
String imageURL = "http://sposter.smartag.my/images/KFC_Voucher.jpg";
String destinationFileName = "C:/Users/sarath_sivan/Desktop/caldophilus.jpg";
downLoadImage(imageURL, destinationFileName);
}
}
Try this at once -
try {
url = paths[0];
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
int length = connection.getContentLength();
InputStream is = (InputStream) url.getContent();
byte[] imageData = new byte[length];
int buffersize = (int) Math.ceil(length / (double) 100);
int downloaded = 0;
int read;
while (downloaded < length) {
if (length < buffersize) {
read = is.read(imageData, downloaded, length);
} else if ((length - downloaded) <= buffersize) {
read = is.read(imageData, downloaded, length
- downloaded);
} else {
read = is.read(imageData, downloaded, buffersize);
}
downloaded += read;
publishProgress((downloaded * 100) / length);
}
Bitmap bitmap = BitmapFactory.decodeByteArray(imageData, 0,
length);
if (bitmap != null) {
Log.i(TAG, "Bitmap created");
} else {
Log.i(TAG, "Bitmap not created");
}
is.close();
return bitmap;
} catch (MalformedURLException e) {
Log.e(TAG, "Malformed exception: " + e.toString());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.toString());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.toString());
}
And, just take a look at here
In ...
FileOutputStream f = new FileOutputStream(new File(root, FILENAME));
Try replacing FILENAME with fileURL.
Also, at which line is the exception thrown? That would help.
String fileURL = "http://sposter.smartag.my/images/KFC_Voucher.jpg";
String FILENAME = "caldophilus.jpg";
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
//c.setDoOutput(true); =========== remove this;
c.connect();
Related
I have the following dowload method that takes an URL and a File. It attempts to resume the file, but if the file is already completed it returns error 416 - Range Not Satisfiable.
How to detect the file is complete?
private void download(final URL source, final File file) throws IOException {
URLConnection connection = source.openConnection();
connection.setConnectTimeout(30);
connection.setReadTimeout(30);
FileOutputStream fos = null;
try {
if (file.exists()) {
fos = new FileOutputStream(file, true);
connection.setRequestProperty("Range", "bytes=" + file.length() + "-");
} else {
fos = new FileOutputStream(file);
}
try (InputStream in = connection.getInputStream()) {
try (BufferedOutputStream bout = new BufferedOutputStream(fos, 1024)) {
byte[] data = new byte[1024];
int x = 0;
while ((x = in.read(data, 0, 1024)) >= 0) {
bout.write(data, 0, x);
}
}
} catch (IOException ioe) {
if (connection instanceof HttpURLConnection) {
var httpUrlConn = (HttpURLConnection) connection;
int response = httpUrlConn.getResponseCode();
if (response == 416) {
}
}
}
} finally {
if (fos != null) {
fos.close();
}
}
}
I am downloading a image file to save in apps internal storage using AsyncTask but I couldn't find the file in my emulator device manager.
here is the code can you tell me exactly where it is saving the image
private class ImageDownloader extends AsyncTask<String,Void,Bitmap>{
HttpURLConnection httpURLConnection;
#Override
protected Bitmap doInBackground(String... strings) {
try {
URL url = new URL(strings[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = new BufferedInputStream(httpURLConnection.getInputStream());
Bitmap temp = BitmapFactory.decodeStream(inputStream);
return temp;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
httpURLConnection.disconnect();
}
return null;
}
In the below example, I will use a lengthy but detailed approach. This approach will enable you to give a file directory manually and allow you to save to a specified directory or path.
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* A utility that downloads a file from a URL.
* #author www.codejava.net
*
*/
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();
}
}
I am new to android.The Image is store in server by Base64 format. so how can i get it from server to My Project and set to my ImageView using Json Object.
Please Help me
Any help will be Appappreciated
Try this:
Convert Url to byte[] first:
byte[] bitmapdata = getByteArrayImage(url);
Method:
private byte[] getByteArrayImage(String url){
try {
URL imageUrl = new URL(url);
URLConnection ucon = imageUrl.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(500);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
return baf.toByteArray();
} catch (Exception e) {
Log.d("ImageManager", "Error: " + e.toString());
}
return null;
}
Now convert the byte[] to bitmap
Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata , 0, bitmapdata .length);
And set your bitmap to your ImageView:
img= (ImageView) findViewById(R.id.imgView);
img.setImageBitmap(bitmap );
I found easy solution:
byte[] img = Base64.decode(userHeader.GetImage(), Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(img, 0, img.length);
imageww.setImageBitmap(getCircleBitmap(bitmap));
Using Apache's commons-io-2.5 lib we can get using this function IOUtils.toByteArray(is)
public static String getByteArrayFromURL(final String url) {
String base64Image = "";
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> result = executor.submit(new Callable<String>() {
public String call() throws Exception {
try {
URL imageUrl = new URL(url);
URLConnection ucon = imageUrl.openConnection();
InputStream is = ucon.getInputStream();
return Base64.encodeToString(IOUtils.toByteArray(is), Base64.NO_WRAP);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
});
try {
base64Image = result.get();
} catch (Exception exception) {
exception.printStackTrace();
}
return base64Image;
}
I have a url of a file which works perfectly in browser and Java SE application but it gives me 403 forbidden error in servlet. Following are the codes of both Java SE program and the servlet
Java SE code
public class UrlDownload {
final static int size=1024;
public static void fileUrl(){
OutputStream outStream = null;
URLConnection uCon = null;
InputStream is = null;
try{
URL Url;
byte[] buf;
int ByteRead,ByteWritten=0;
Url= new URL("http://o-o---preferred---bharti-del2---v17--- lscache7.c.youtube.com/videoplayback?upn=6BFud0UQ_-0&sparams=cp%2Cgcr%2Cid%2Cip%2Cipbits%2Citag%2Cratebypass%2Csource%2Cupn%2Cexpire&fexp=900147%2C907217%2C922401%2C919804%2C920704%2C912806%2C906831%2C911406%2C913550%2C912706&key=yt1&itag=37&ipbits=8&signature=6EBF4572274A427AFF58E023CEC8B62439E0B914.BD6827306B81393BE3998FA0F0701E6F2701A3F8&mv=m&sver=3&mt=1345685891&ratebypass=yes&source=youtube&ms=au&gcr=in&expire=1345708167&ip=116.203.237.173&cp=U0hTSldLVl9LUUNOM19PRVpCOkV6WE5pcUF1NjQ5&id=9d8c9310d90eae67&quality=hd1080&fallback_host=tc.v17.cache7.c.youtube.com&type=video/mp4");
outStream = new BufferedOutputStream(new
FileOutputStream("video"));
uCon = Url.openConnection();
is = uCon.getInputStream();
buf = new byte[size];
while ((ByteRead = is.read(buf)) != -1)
{
System.out.println("Downloading file");
outStream.write(buf, 0, ByteRead);
ByteWritten += ByteRead;
}
System.out.println("Downloaded Successfully.");
}catch (Exception e) {
e.printStackTrace();
}finally {
try {
is.close();
outStream.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
}
Servlet Code
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("video/mp4");
String url=request.getParameter("url");
URLConnection con = null;
BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
InputStream in=null;
byte[] buffer;
int ByteRead,ByteWritten=0;
try {
URL dUrl=new URL(url);
con=dUrl.openConnection();
in=con.getInputStream();
buffer = new byte[1024];
while ((ByteRead = in.read(buffer)) != -1)
{
System.out.println("Downloading file");
out.write(buffer, 0, ByteRead);
ByteWritten += ByteRead;
}
} finally {
out.close();
in.close();
}
}
url is the same url given as a parameter to this servlet
YouTube download URLs are intended for one-time use only -- they are bound to the IP range that they were initially generated for, and expire after some time. Hard-coding one in your application, as you've done here, will lead to inevitable failure.
I have this method that downloads .csv files from yahoo finance and saves them locally. It is accessed during a loop so it is downloading many files from a list. However sometimes a symbol is entered incorrectly, no longer exists, or the connection times out. How can I amend this method so that connection time outs are retried and incorrect symbols (meaning the url does not work) are just skipped over without ending the program?
public static void get_file(String symbol){
OutputStream outStream = null;
URLConnection uCon = null;
InputStream is = null;
String finance_url = "http://ichart.finance.yahoo.com/table.csv?s="+symbol;
String destination = "C:/"+symbol+"_table.csv";
try {
URL Url;
byte[] buf;
int ByteRead,ByteWritten=0;
Url= new URL(finance_url);
outStream = new BufferedOutputStream(new FileOutputStream(destination));
uCon = Url.openConnection();
is = uCon.getInputStream();
buf = new byte[size];
while ((ByteRead = is.read(buf)) != -1) {
outStream.write(buf, 0, ByteRead);
ByteWritten += ByteRead;
}
}catch (Exception e) {
System.out.println("Error while downloading "+symbol);
e.printStackTrace();
}finally {
try {
is.close();
outStream.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
Why not call the method again when an exception is thrown. You can narrow down the exception type to indicate when a retry should be initiated.
public static void get_file(String symbol){
OutputStream outStream = null;
URLConnection uCon = null;
InputStream is = null;
String finance_url = "http://ichart.finance.yahoo.com/table.csv?s="+symbol;
String destination = "C:/"+symbol+"_table.csv";
try {
URL Url;
byte[] buf;
int ByteRead,ByteWritten=0;
Url= new URL(finance_url);
outStream = new BufferedOutputStream(new FileOutputStream(destination));
uCon = Url.openConnection();
is = uCon.getInputStream();
buf = new byte[size];
while ((ByteRead = is.read(buf)) != -1) {
outStream.write(buf, 0, ByteRead);
ByteWritten += ByteRead;
}
}catch (Exception e) {
getFile(symbol);
}finally {
try {
is.close();
outStream.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}