0

I want to download picture from URL - direct link to a picture. It is somehow protected, when I try :

InputStream in = new URL("http://www.somesite.sk/somepicture.jpg") 
Files.copy(in, Paths.get("C:/picture.jpg"));

it downloads, but not as the original picture, the file "picture.jpg" has only this text inside :

<head><title>Document Moved</title></head>
<body><h1>Object Moved</h1>This document may be found <a HREF="http://www.somesite.sk/somepicture.jpg">here</a></body>

when I try direct download - right mouse-click and Save Picture, it works, if I try some download manager, it works. Some idea?

nilrem
  • 21
  • 5
  • 1
    I wouldn't mind an actual link to the image to try some things out in order to answer your question. Would it be possible to have one? My first guess is a User Agent problem. – Azami Nov 11 '16 at 22:24
  • 1
    use another httpClient and make sure you Enable the redirect following. See here to get samples - http://www.baeldung.com/httpclient-stop-follow-redirect – Sergey Benner Nov 11 '16 at 22:26
  • MadWard : http://www.temponabytok.sk/Files/obrazky/10010483.jpg – nilrem Nov 11 '16 at 22:33
  • Looks like a duplicate of http://stackoverflow.com/questions/1884230/urlconnection-doesnt-follow-redirect . The Location header contains the same URL with an `https` scheme. Using the https URL directly is one possible workaround. – VGR Nov 11 '16 at 22:50
  • VGR : great, it was exactly the problem, didn't realized, thanks – nilrem Nov 12 '16 at 06:09

1 Answers1

0

Just tested it. Put these dependencies into your pom.xml file.

    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.5</version>
    </dependency>

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.3.2</version>
    </dependency>

import org.apache.commons.io.FileUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import java.io.File;

public class ImageDownloader {   
    public static void main(String[] args) {    
        HttpClient instance = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet("https://yourhost.blah/yuorfile.jpg");
        try {
            HttpResponse response = instance.execute(httpGet);
            FileUtils.copyInputStreamToFile(response.getEntity().getContent(), new File("output.jpg"));    
        } catch (Exception e) {
            e.printStackTrace();
        }    
    }   
}

hope it helps

Sergey Benner
  • 4,421
  • 2
  • 22
  • 29