我想从网址下载图片 - 直接链接到图片。 当我尝试时,它以某种方式受到保护:
InputStream in = new URL("http://www.somesite.sk/somepicture.jpg")
Files.copy(in, Paths.get("C:/picture.jpg"));
它下载了,但不是原始图片,文件“picture.jpg”里面只有这个文字:
<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>
当我尝试直接下载时 - 右键单击并保存图片,它可以工作,如果我尝试一些下载管理器,它的工作原理。 有些想法?
答案 0 :(得分:0)
刚试过它。将这些依赖项放入pom.xml文件中。
<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();
}
}
}
希望有所帮助