How to download excel (.xls) file from API in postman?

前端 未结 4 1701
眼角桃花
眼角桃花 2020-12-02 05:48

I am having an API endpoint and Authorization token for that API.

The said API is for .xls report download, how can I view the downloaded .xls

4条回答
  •  臣服心动
    2020-12-02 06:27

    If the endpoint really is a direct link to the .xls file, you can try the following code to handle downloading:

    public static boolean download(final File output, final String source) {
        try {
            if (!output.createNewFile()) {
                throw new RuntimeException("Could not create new file!");
            }
            URL url = new URL(source);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // Comment in the code in the following line in case the endpoint redirects instead of it being a direct link
            // connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("AUTH-KEY-PROPERTY-NAME", "yourAuthKey");
            final ReadableByteChannel rbc = Channels.newChannel(connection.getInputStream());
            final FileOutputStream fos = new FileOutputStream(output);
            fos.getChannel().transferFrom(rbc, 0, 1 << 24);
            fos.close();
            return true;
        } catch (final Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    

    All you should need to do is set the proper name for the auth token and fill it in.

    Example usage:

    download(new File("C:\\output.xls"), "http://www.website.com/endpoint");
    

提交回复
热议问题