在java中下载图像

我必须从 nasa 网站下载一张图片。问题是,我的代码有时可以工作,成功下载图像,而有时只保存 186B(不知道为什么是 186)。


问题肯定与美国国家航空航天局 (nasa) 保存这些照片的方式有关。例如,来自该链接 https://mars.jpl.nasa.gov/msl-raw-images/msss/00001/mcam/0001ML0000001000I1_DXXX.jpg 的图像已成功保存,而来自该链接https://mars.nasa .gov/mer/gallery/all/2/f/001/2F126468064EDN0000P1001L0M1-BR.JPG失败。


这是我的代码


public static void saveImage(String imageUrl, String destinationFile){

    URL url;

    try {

        url = new URL(imageUrl);

        System.out.println(url);

        InputStream is = url.openStream();

        OutputStream os = new FileOutputStream(destinationFile);


        byte[] b = new byte[2048];

        int length;


        while ((length = is.read(b)) != -1) {

            os.write(b, 0, length);

        }


        is.close();

        os.close();

    } catch (MalformedURLException e) {

        // TODO Auto-generated catch block

        e.printStackTrace();

    } catch (IOException e) {

        // TODO Auto-generated catch block

        e.printStackTrace();

    }


}

有人有想法,为什么不起作用?


public boolean downloadPhotosSol(int i) throws JSONException, IOException {

    String url0 =  "https://api.nasa.gov/mars-photos/api/v1/rovers/spirit/photos?sol=" + this.chosenMarsDate + "&camera=" + this.chosenCamera + "&page=" + i + "&api_key=###";

    JSONObject json = JsonReader.readJsonFromUrl(url0);

    if(json.getJSONArray("photos").length() == 0) return true;

    String workspace = new File(".").getCanonicalPath();

    String pathToFolder = workspace+File.separator+this.getManifest().getName() + this.chosenMarsDate + this.chosenCamera +"Strona"+i;

    new File(pathToFolder).mkdirs();

    for(int j = 0;j<json.getJSONArray("photos").length();j++) {

        String url = ((JSONObject) json.getJSONArray("photos").get(j)).getString("img_src");

        SaveImage.saveImage(url, pathToFolder+File.separator+"img"+j+".jpg");

    }

    return false;

}


ITMISS
浏览 100回答 2
2回答

互换的青春

当你得到一个 186 字节的文件时,用文本编辑器打开它,看看里面有什么。它可能包含 HTML 格式的 HTTP 错误消息。相反,如果您看到图像文件的前 186 个字节,则说明您的程序有问题。编辑:从您的评论看来,您正在收到一个 HTTP 301 响应,这是一个重定向到另一个位置的响应。Web 浏览器会在您不注意的情况下自动处理此问题。但是,您的 Java 程序未遵循重定向到新位置。您需要使用处理重定向的 HTTP Java 库。

绝地无双

最好和最简单的方法:try(InputStream in = new URL("http://example.com/image.jpg").openStream()){&nbsp; &nbsp; Files.copy(in, Paths.get("C:/File/To/Save/To/image.jpg"));}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java