Home > Net >  AWS S3 file download via Java. Failing on Authentication call
AWS S3 file download via Java. Failing on Authentication call

Time:12-20

I'm trying to download a JSON file from an AWS S3 bucket through Java.

The file is created by a 3rd party billing application called Zuora.

The first step is to use OAuth credentials to generate the file. I then get a response with the file URL. I can access this via the browser and download it to my desktop, but when I try to process the file via Java I'm running into issues.

Everywhere I look online I see that people seem to have overcome similar issues by using AmazonS3Client from the AWS libraries. Ref: enter image description here

There is no need for creds here.

import javax.swing.*;
 import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

class Swing implements ActionListener {
        JFrame frame=new JFrame();
        JButton button=new JButton("Click Me");

        Swing(){
            prepareGUI();
            buttonProperties();
        }

        public void prepareGUI(){
            frame.setTitle("My Window");
            frame.getContentPane().setLayout(null);
            frame.setVisible(true);
            frame.setBounds(200,200,400,400);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
        public void buttonProperties(){
            button.setBounds(130,200,100,40);
            frame.add(button);
            button.addActionListener(this);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            //Get a presigned PDF from an Amazon S3 bucket.
            try {
                URL url  =  new URL("<Specify PRESIGNED URL> ") ;
                InputStream in = null;
                in = url.openStream();
                FileOutputStream fos = new FileOutputStream(new File("C:\\AWS\\yourFile2.txt"));
                System.out.println("reading from resource and writing to file...");
                int length = -1;
                byte[] buffer = new byte[1024];// buffer for portion of data from connection
                while ((length = in.read(buffer)) > -1) {
                    fos.write(buffer, 0, length);
                }
                fos.close();
                in.close();
                 System.out.println("File downloaded");
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    public class HelloWorldSwing {
        public static void main(String[] args)
        {
            new Swing();
        }
    }
  • Related