I'm trying to download an imagen in java,using a function,
here is my code to send the function
saveImage(newString, folder.toString());
then, this is my function saveImage
public static void saveImage(String imageUrl,String folderpath) throws IOException {
URL url = new URL(imageUrl);
//String destName = folder;
//System.out.println(destName);
InputStream is = url.openStream();
OutputStream os = new FileOutputStream(folderpath);
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}
is.close();
os.close();
}
i tried from links here at stackoverflow, but anything works, all the time i got a
java.io.IOException: Server returned HTTP response code: 403 for URL
how can i fix it? the Exception, thank you
A 403 Forbidden HTTP status return code from a web server indicates that the server can be reached but refuses to take any action due to the web server being configured to deny access, for whatever reason, to the requested resource.
So there's nothing wrong with the code that you showed us, it's to do with the configuration of the web server that you're trying to get the image from.
Try using an Authenticator in order to set the authenticator default that will be used for all requests. You will need a user name and password.
It can be used something like this:
Authenticator.setDefault(new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
"user", "password".toCharArray());
}
});
here is the code to fix it, if anyone want to use it.
public static void saveImage(String imageUrl, File folder, String m) throws IOException {
if (!folder.exists()) {
folder.mkdirs();
System.out.println("si quedo con el if folderpath----" + folder);
}
URL url = new URL(imageUrl);
//String destName = folder;
//System.out.println(destName);
m = m + ".jpg";
//final URL url = new URL(urlStr);
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (compatible; MSIE 6.0; Windows NT 5.0)");
final BufferedImage image = ImageIO.read(connection.getInputStream());
ImageIO.write(image, "jpg", new File(m));
}
Related
I'm developing a small test to download an apk from apkpure using java.
The URL that I have, returns a 403. But on the browser, it works fine. All solutions I tried did not work.
Here is the code:
URL url = new URL(TheUrl);
try (InputStream in = url.openStream()) {
Files.copy(in, Paths.get(apkPathInFolder), StandardCopyOption.REPLACE_EXISTING);
System.out.println("test ok");
} catch (IOException e) {
// handle exception
System.out.println(e);
}
How could I handle it, please ?
Thanks
An example of the URL I have as input.
The default Java user-agent is blocked by some online services. You need to set the User-Agent header to something else:
URL url = new URL(httpUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("User-Agent", "my-agent");
httpURLConnection.connect();
try (InputStream in = httpURLConnection.getInputStream()) {
Full code:
public static void main(String[] args) throws IOException {
URL url = new URL("https://download.apkpure.com/b/APK/Y29tLnRlbmNlbnQuaWdfMTU1MjNfYmFhM2U4Njk?_fn=UFVCRyBNT0JJTEUgUkVTSVNUQU5DRV92MS42LjBfYXBrcHVyZS5jb20uYXBr&as=1e5ab5a5ef235ad0674f6ed4f7ff59576150d1cd&ai=33533981&at=1632686421&_sa=ai%2Cat&k=06ee0e1f9f5964c4edc23905822a9c8861537455&_p=Y29tLnRlbmNlbnQuaWc&c=2%7CGAME_ACTION%7CZGV2PVBST1hJTUElMjBCRVRBJnQ9YXBrJnM9MTEzMjQ5NjAwMiZ2bj0xLjYuMCZ2Yz0xNTUyMyZodD1lMDE&ht=e01");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("User-Agent", "my-agent");
httpURLConnection.connect();
try (InputStream in = httpURLConnection.getInputStream()) {
Files.copy(in, Paths.get("/home/user/Documents/files/my-apk.apk"), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
// handle exception
System.out.println(e);
}
}
you can get the header from browser and set it in you code.
if you use chrome browser, open the dev tools in your request page.
This should be an easy learning task but something went wrong:
Use API request to get image from some link and check it is in Base64 standard.
private static void getRequest() throws IOException {
URL url = new URL("http://apimeme.com/meme?meme=Alarm-Clock&top=Top+text&bottom=Bottom+text");
InputStream is = (InputStream) url.openStream();
FileInputStream imageInFile = new FileInputStream(is.toString());
byte imageData[] = new byte[2048];
imageInFile.read(imageData);
System.out.println(isBase64(imageInFile.toString()));
}
static boolean isBase64(String path) {
try {
Base64.getDecoder().decode(path);
return true;
} catch(IllegalArgumentException e) {
return false;
}
}
Right now problem is on line
InputStream is = (InputStream) url.openStream();
Server sends 403. How to fix this? Method isBase64 should work but the program doesn't reach this line.
Your need 3 header for avoid http 403 error code
private static void getRequest() throws IOException {
URL url = new URL("http://apimeme.com/meme?meme=Alarm-Clock&top=Top+text&bottom=Bottom+text");
URLConnection is = url.openConnection();
is.setRequestProperty("Host", "apimeme.com");
is.setRequestProperty("Cookie", "*");
is.setRequestProperty("User-Agent", "*");
byte[] imageData = new byte[2048];
File downloadFile = new File("download.png");
FileOutputStream outputStream = new FileOutputStream(downloadFile);
int read;
while ((read = is.getInputStream().read(imageData)) != -1) {
outputStream.write(imageData, 0, read);
}
outputStream.close();
System.out.println(isBase64(downloadFile.getAbsolutePath()));
}
403 is means that you do not have permission to view this URL. You cannot do anything to fix this client side, even authorization would not help (if the ressource required authorization, the server would send 401 instead). So to fix the issue, whoever is in charge of the web server delivering the URL you're trying to access will have to fix this - if they think you should have access.
I'm trying to download a zip file through a java program using GitHub API.
The program I'm using is the following:
public static void main(String[] args) {
// create client
HttpClient client = HttpClient.newHttpClient();
// create request
HttpRequest request = HttpRequest.newBuilder().uri(URI.create("https://api.github.com/repos/:owner/:repo/zipball/:ref")).build();
// use the client to send the asynchronous request
InputStream is = client.sendAsync(request, BodyHandlers.ofInputStream())
.thenApply(HttpResponse::body).join();
try {
FileOutputStream out = new FileOutputStream("outputZipFile.zip");
copy(is,out,1024);
out.close();
}catch(Exception e) {}
}
private static void copy(InputStream is, FileOutputStream out, int i) {
// TODO Auto-generated method stub
byte[] buf = new byte[i];
try {
int n = is.read(buf);
while(n>=0) {
out.write(buf,0,n);
n=is.read(buf);
}
out.flush();
}catch(IOException ioe) {
System.out.println(ioe.getStackTrace());
}
}
When I try to run this I get empty body so the output file will be empty as well.
I noticed that using HttpURLConnection insted of Java11 HttpClient makes it work but I'd prefer to use this Java11 feature in order to send asynchronous requests.
I can't understand what I'm doing wrong.
EDIT: The HttpURLConnection code I'm using at the moment is the following:
private void downloadVersion(String sha, String outputDestination) {
try {
URL url = new URL( getDownloadQuery(sha) );
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
if(authToken!=null)
connection.setRequestProperty("Authorization", "Bearer " + authToken) ;
connection.setRequestMethod("GET");
InputStream in = connection.getInputStream();
FileOutputStream out = new FileOutputStream(outputDestination);
copy(in, out, 1024);
out.close();
} catch (Exception e) {}
}
Your url (when set to correct github repos) may be returning redirect status 302. To make HTTP client follow redirects replace HttpClient client = HttpClient.newHttpClient() with use of HttpClient.newBuilder(). You can also simplify your code with try with resources and making use of InputStream.transferTo:
HttpClient client = HttpClient.newBuilder().followRedirects(Redirect.ALWAYS).build();
URI uri = URI.create("https://api.github.com/repos/:owner/:repo/zipball/:ref");
HttpRequest request = HttpRequest.newBuilder().uri(uri).build();
// use the client to send the asynchronous request
InputStream is = client.sendAsync(request, BodyHandlers.ofInputStream())
.thenApply(HttpResponse::body).join();
try (FileOutputStream out = new FileOutputStream("outputZipFile.zip")) {
is.transferTo(out);
}
I'm trying to make a POST-request using android HttpUrlConnection. First I use the example for GET-request from here:
http://developer.android.com/training/basics/network-ops/connecting.html#http-client
It works perfectly (for example I get google.com page). Then I make some changes to make a POST-request: change the request method on POST:
conn.setRequestMethod("POST");
and add this code (got from here: http://developer.android.com/reference/java/net/HttpURLConnection.html):
conn.setDoOutput(true);
conn.setChunkedStreamingMode(0);
OutputStream out = new BufferedOutputStream(conn.getOutputStream());
out.close();
So now the method downloadUrl looks like this:
private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
// Only display the first 500 characters of the retrieved
// web page content.
int len = 500;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setChunkedStreamingMode(0);
OutputStream out = new BufferedOutputStream(conn.getOutputStream());
out.close();
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.d(DEBUG_TAG, "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
return contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
And it always throws IOException. Could you help me, what is wrong?
It's because Android won't let you start a network connection on the main UI thread. You have to start a background thread (use AsyncTask) and do it from there.
More detail in this question.
I've sold this problem: the thing was the server didn't accept POST-requests on the selected URL. Changing URL (and server) led to successful request without throwing an exception.
I already success display thumbnail video from URL on my android app when internet connection is connected, but when internet connection is off the thumbnail doesn't display.
here is my code.
Bitmap bmThumbnail;
bmThumbnail = ThumbnailUtils.createVideoThumbnail("http://somedomain.com/video/myvideo.mp4", Thumbnails.MICRO_KIND );
imgPhoto.setImageBitmap(bmThumbnail);
i want the thumbnail still display although connection is off,there is away to achieve like save the cache on sdcard first, like image cache does? or any other solution to show thumbnail video when internet connection is off?
thanks,
public static String getBitmapFromURL(final Activity activity, String link,
String filename) throws FileNotFoundException,
MalformedURLException, IOException {
/*--- this method downloads an Image from the given URL,
* then decodes and returns a Bitmap object
---*/
File file = null;
file = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath()
+ CommonVariable.KCS_IMAGE_FOLDER_NAME_PHONE_MEMORY);
// have the object build the directory structure, if needed.
if (!file.exists()) {
file.mkdirs();
}
// create a File object for the output file
File outputFile = new File(file, filename);
FileOutputStream fos = new FileOutputStream(outputFile);
BufferedOutputStream out = new BufferedOutputStream(fos, 1024);
URL url = new URL(link);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
out = new BufferedOutputStream(fos, 1024);
int b;
while ((b = input.read()) != -1) {
out.write(b);
}
out.close();
connection.disconnect();
return outputFile.getAbsolutePath();
}
use this function,it will return string of sdcard path.and use this path u can set bitmap image using below function:
public static void setImagesNew(ImageView img, String pathName,
Activity activity) {
Bitmap bmThumbnail = ThumbnailUtils.createVideoThumbnail(pathName, Thumbnails.MICRO_KIND );
img.setImageBitmap(bmThumbnail);
bmp = null;
System.gc();
Runtime.getRuntime().gc();
}
i hope this is useful to you...............