Getting 403(Forbidden) error on get Request from cloudFlare

344 Views Asked by At

I have an image uploaded to an S3 bucket, and I want to access that image via Cloudflare (CDN). When I attempt to view the image by entering the URL in a browser or using Postman, I can see the image without any issues.

However, when I try to fetch it using Java in a Spring Boot application, I encounter a 403 error.

I tried 3 ways to fetch image

1.

Image.getInstance(imageUrl)
  1.           RestTemplate restTemplate = new RestTemplate();
              HttpHeaders headers = new HttpHeaders();
              headers.set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36");
              HttpEntity<String> entity = new HttpEntity<>(headers);
              byte[] imageData = restTemplate.exchange(imageUrl, HttpMethod.GET, entity, byte[].class).getBody();
    
  2.           URL url = new URL(logoPath);
              URLConnection connection = url.openConnection();
              InputStream inputStream = connection.getInputStream();
              FileOutputStream outputStream = new FileOutputStream("image.png");
              byte[] buffer = new byte[1024];
              int bytesRead;
              while ((bytesRead = inputStream.read(buffer)) != -1) {
                  outputStream.write(buffer, 0, bytesRead);
              }
              inputStream.close();
              outputStream.close();
    

In approach 1&3 I'm getting 401(Forbidden) . In approach 2 , getting 301

What can i do to resolve this issue ?

I want to fetch this image to directly use in File .

1

There are 1 best solutions below

0
On

I solved this error by adding a " user agent " while creating connection or headers.

I also tried with adding multiple user agent but it didn't work for me . Try to add only one user Agent .

          RestTemplate restTemplate = new RestTemplate();
          HttpHeaders headers = new HttpHeaders();
          headers.set("User-Agent", "Mozilla/5.0 ");
          HttpEntity<String> entity = new HttpEntity<>(headers);
          byte[] imageData = restTemplate.exchange(imageUrl, HttpMethod.GET, entity, byte[].class).getBody();