ResponseCode 400 for downloading image from url [duplicate] - java

This question already has answers here:
What exactly does URLConnection.setDoOutput() affect?
(4 answers)
Closed 12 months ago.
This is the code I wrote for downloading image from url, but receving response code 400 with java.io.FilenotFoundException
#Override
protected Void doInBackground(String... strings) {
try {
URL url = new URL(strings[0]);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("User-Agent", "Mozilla/5.0
(Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2)
Gecko/20100316 Firefox/3.6.2");
con.setRequestMethod("GET");
con.setDoOutput(true);
con.connect();
File file = Environment.getExternalStorageDirectory();
File f1 = new File(file, "_Url download");
if(!f1.exists()){
f1.mkdir();
}
fileName = System.currentTimeMillis() + ".jpg";
File f2 = new File(f1, fileName);
f2.createNewFile();
InputStream er = con.getErrorStream();
Log.i("ErrorCode", con.getResponseCode()+"");
Log.i("ErrorMessage", con.getResponseMessage());
Log.i("ErrorStream", er+"");
InputStream in = con.getInputStream();
FileOutputStream out = new FileOutputStream(f2);
byte[] buffer = new byte[1024];
int len;
System.out.println(Arrays.toString(buffer));
while((len = in.read(buffer, 0, 1024)) > 0) {
out.write(buffer, 0, len);
}
out.close();
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
Log.i("IOException", e.toString());
}
return null;
}
LOG
2021-06-26 09:26:25.532 26760-26890/com.example.urldownload I/ErrorCode: 400
2021-06-26 09:26:25.533 26760-26890/com.example.urldownload I/ErrorMessage: Bad Request
2021-06-26 09:26:25.533 26760-26890/com.example.urldownload I/Errorstream: buffer(com.android.okhttp.internal.http.Http1xStream$FixedLengthSource#fbb2c70).inputStream()
2021-06-26 09:26:25.534 26760-26890/com.example.urldownload I/IOException: java.io.FileNotFoundException: https://instagram.fidr1-1.fna.fbcdn.net/v/t51.2885-15/e35/190664842_184685183538740_5039921250568173600_n.jpg?tp=1&_nc_ht=instagram.fidr1-1.fna.fbcdn.net&_nc_cat=108&_nc_ohc=RrEU4lTwYCwAX-vgVQ4&edm=AABBvjUBAAAA&ccb=7-4&oh=3ac34be54793fa59134380fd9e0bd617&oe=60DCB7E6&_nc_sid=83d603
Manifest
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
Image of the file where the image is being saved
For more details look at this image
what should I do to resolve this error or is there any better way to do this

I got my mistake.
Thank you everyone for sharing your ideas
con.setDoOutput(true); is a POST method
And it doesn't fetches any data
con.setDoOutput(true); should not be used.

Use picasso to save images in external storage, you can do something like following
private Target mTarget = new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
// Perform simple file operation to store this bitmap
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
}
...
Picasso.with(this).load("url").into(mTarget);
Here "Target" is a class provided by picasso, and it has very simple method to understand...
This is a easy way to do

It is hard to figure out what might be causing the error due to lack of provided code. My best guess would be to use DownloadManager instead of AsyncTask.
The download manager is a system service that handles long-running HTTP downloads. Clients may request that a URI be downloaded to a particular destination file. The download manager will conduct the download in the background, taking care of HTTP interactions and retrying downloads after failures or across connectivity changes and system reboots. (https://developer.android.com/reference)

Related

How to Download Audio from URL using android

I'm new to android and for trainning i want to create an app that downloads audio from existing api.
i'm getting the link to downloading the file from the api, but i can't get it download properly
i've tried with download manager, in which, didn't even download it although it said it did.
here's the main code:
public void Download(String link)
{
downloadManager = (DownloadManager)m_context.getSystemService(m_context.DOWNLOAD_SERVICE);
Uri Download_Uri = Uri.parse(link);
DownloadManager.Request request = new DownloadManager.Request(Download_Uri);
//Restrict the types of networks over which this download may proceed.
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
//Set whether this download may proceed over a roaming connection.
request.setAllowedOverRoaming(false);
//Set the title of this download, to be displayed in notifications (if enabled).
request.setTitle("Downloading " + m_name);
//Set a description of this download, to be displayed in notifications (if enabled)
request.setDescription("Downloader");
//Set the local destination for the downloaded file to a path within the application's external files directory
request.setDestinationInExternalFilesDir(m_context, Environment.DIRECTORY_DOWNLOADS, m_name +".mp3");
//Enqueue a new download and same the referenceId
downloadReference = downloadManager.enqueue(request);
}
m_context is MainActivity
link is url that contains the file for downloading.
I'm using broadcast receiver to see if the download completed, and it did so i try to open it but nothing happens.
I've also tried to download it without the DownloadManager, even though it downloaded it, the size is very very small (1-15 kb) but sometimes(not most of the time maybe 5%) it gives me the complete audio(according to size and time)
here's the code:
public void Download(final String link)
{
try {
Thread t= new Thread(){
public void run() {
int count;
try {
URL url = new URL(link);
URLConnection conexion = url.openConnection();
Thread.sleep(20000);
conexion.connect();
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = conexion.getContentLength();
// downlod the file
InputStream input = new BufferedInputStream(url.openStream());
String storageState = Environment.getExternalStorageState();
if (storageState.equals(Environment.MEDIA_MOUNTED)) {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/Music",m_name+".mp3");
OutputStream output = new FileOutputStream(file);
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();
}
} catch (Exception e) {
downloadSuccess = false;
e.printStackTrace();
}
}
};
t.start();
t.join();
} catch (InterruptedException e) {
downloadSuccess = false;
e.printStackTrace();
}
}
you will see thread.sleep, i've assumed that the response needs a little time to process but even a minute didn't finish.
Any guidance will be appreciated
Thank you
UPDATE:
There's something called GZIPInputStream that the encoding of the files that failed download correctly are in gzip
peace of code:
if ("gzip".equals(httpConn.getContentEncoding())) {
BufferedReader in= new BufferedReader(new InputStreamReader(new GZIPInputStream(httpConn.getInputStream())));
StringBuilder sb = new StringBuilder();
String read;
while ((read = in.readLine()) != null){
sb.append(read);
}
}
it's still not helping me to download in the correct way but i think it's the right path, and again any help will be great. thank you

Wrong Mime-Type when downloading binary file on mobile data (Android)

I'm trying to download a binary file using:
URL url = new URL(urlStr);
HttpURLConnection ucon = (HttpURLConnection) url.openConnection();
ucon.connect();
InputStream is = new BufferedInputStream(ucon.getInputStream());
When run via mobile data (on Samsung Galaxy 4, Android 5.0.1) I receive the following response
j���UFEHLER��6ERROR��`Заявеното съдържание не може да бъде заредено ��&Wrong MIME-Type���Fback��2
Which means "The content requested cannot be loaded" in Bulgarian (the server I download from is Bulgaria). But more informative seems "Wrong MIME-Type" at the end of the response.
I tried the same using HttpGet with no result.
The weird thing is everything is ok when I execute the same request via Wifi.
Also I can download the file from the brower on mobile data, but not for the code. Also I've tested on Lenovo with Android 4.4.2 via mobile data and is also worked.
I noticed I'm getting Content-Type: application/vnd.wap.wmlc (logged ucon.getResponseCode()) when connected via mobile data and nothing set as content type when via WiFi.
Any ideas? :/
Here's my working code for file downloading. You can have a look to check if you're missing something.
public class ImageDownloaderAsyncTask extends
AsyncTask<Void, Integer, Integer> {
private static File f;
protected void doInBackground() throws IOException {
File dir = new File(Constants.FILE_PATH);
if (!dir.exists()) dir.mkdir();
f = new File(Constants.FILE_PATH + Constants.FILE_NAME);
if (f != null && !f.exists()) {
f.createNewFile();
}
try {
URL url = new URL(fileUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
String data1 = f.getPath();
FileOutputStream stream = new FileOutputStream(data1);
byte data[] = new byte[4096];
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
}
stream.write(data, 0, count);
}
stream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected Integer doInBackground(Void... params) {
try {
doInBackground();
} catch (IOException e) {
e.printStackTrace();
}
return 1;
}
protected void onPostExecute(Integer result) {}
}

Android: simplest url download without progress bar

I have tried to implement over 10-15 different download mechanisms for android java, I have not been able to succeed at all.
I don't care about progress bars or background processes.
I just want one functional download code in fewest lines possible
and I want it to download a binary file (foreground) to the directory in the device wherever it can be accessed as
File pf = new File("filename");
if (pf.exists()) { ... }
Try this (modified from here):
try {
URL url = new URL("http://url.com");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
//THIS IS WHERE YOU GET THE DIRECTORY TO SAVE TO
File SDCardRoot = Environment.getExternalStorageDirectory();
//THIS IS WHERE YOU WILL SET THE FILE NAME
File file = new File(SDCardRoot,"somefile.txt");
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
You may also need to add permissions to access the phone directory:
<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
For information on accessing certain folders on the internal directory, see the android developer page: http://developer.android.com/training/basics/data-storage/files.html#WriteInternalStorage
In fact, the solution on that page is also fairly short:
String filename = "myfile";
String string = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}

How to download and stock a jar file into internal storage?

I am trying to download a jar file from my server and put it into the AVD internal memory but it's not working. I tried this code in Java and it's working perfectly.
try
{
URL url = new URL(host);
URLConnection connection = url.openConnection();
int fileLength = connection.getContentLength();
if (fileLength == -1)
{
return;
}
input = connection.getInputStream();
String fileName = url.getFile().substring(url.getFile().lastIndexOf('/') + 1);
writeFile = new FileOutputStream(fileName);
byte[] buffer = new byte[1024];
int read;
while ((read = input.read(buffer)) > 0)
writeFile.write(buffer, 0, read);
writeFile.flush();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
writeFile.close();
input.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
I add the following permission into my manifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
But on connection.getContentLength();, I got a NullPointerException return
I tried with HttpURLConnection and JarURLConnection, add a connection.connect() just after openConnection(), using DownloadManager but it can only download into external storage.
Maybe with HttpClient ? AndroidHttpClient ? But Android support recommend using HttpURLConnection for applications targeted at Gingerbread and higher.
There's a cumbersome but straightforward approach:
1. Use DownloadManager to get a JAR you need (store it in external storage);
2. Move that JAR from external storage to internal one.

Downloading an image in android

I have make an application in which I require to download an image from a given link . Its showing no errors an no error messages in logcat. Following is my code
public Drawable getImage(String ImagePath,String fileName) {
Log.v("download", "image downloading from net");
boolean bin = getBinaryWebFile(ImagePath,fileName);
Drawable draw = Drawable.createFromPath(SavePath+fileName); //..........(1)
return draw;
}//getImage ends here*/
private boolean getBinaryWebFile(String inURL, String filename) {
File file = new File(SavePath,filename);
try {
URL url = new URL(inURL);
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setRequestMethod("GET");
con.setDoOutput(true);
con.connect();
InputStream is = con.getInputStream();
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bout = new BufferedOutputStream(fos,1024);
byte[] data =new byte[1024];
int x = 0;
while((x=is.read(data,0,1024))>=0){
bout.write(data,0,x);
}
fos.flush();
bout.flush();
fos.close();
bout.close();
is.close();
return true;
} catch (MalformedURLException e) {
Log.d("PowerSaver","getBinaryWebFile->MalformedURLException: "+e.getMessage());
//e.printStackTrace();
} catch (IOException e) {
Log.d("PowerSaver","getBinaryWebFile->I/O exception: "+e.getMessage());
}
return false;
}//getbinarywebfile ends here
On debugging everything is running fine and at last I am getting draw as null (commented as 1) . I have even written the following permmission in manifest .
<uses-permission
android:name = "android.permission.INTERNET"/>
<uses-permission
android:name = "android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission
android:name = "android.permission.ACCESS_WIFI_STATE" />
<uses-permission
android:name = "android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission
android:name = "android.permission.READ_PHONE_STATE"/>
still getting null in draw which is referenced as comment 1.
This code works for me:
private static long DownloadFromUrl(Context context, URL fileUrl,
String fileName) throws Exception { // this is the downloader method
try {
URL myFileUrl = null;
myFileUrl = fileUrl;
// *** Internet connection
HttpURLConnection conn = (HttpURLConnection) myFileUrl
.openConnection();
conn.setDoInput(true);
conn.connect();
// int length = conn.getContentLength();
// int[] bitmapData =new int[length];
// byte[] bitmapData2 =new byte[length];
InputStream is = conn.getInputStream();
// decodificar la imagen de internet en bmImg
Bitmap bmImg = BitmapFactory.decodeStream(is);
// ***Save in the the SD
FileOutputStream out = new FileOutputStream(
<path + filename>);
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) > 0) {
out.write(buffer, 0, len);
tam += len;
}
is.close();
// Save using the selected format and quality
bmImg.compress(Bitmap.CompressFormat.PNG,
<quality>, out);
out.flush();
out.close();
// tam=bmImg.getByteCount();
bmImg.recycle();
return tam;
} catch (IOException e) {
// showErrorMessage(context, "Error downloading");
e.printStackTrace();
return 0;
}
}
Are you running your app inside the emulator? Make sure it has a proper internet connection. Sometimes the emulator can loose internet connectivtiy, especially when you're changing networks without restarting the emulator.

Categories

Resources