How to get an image file from an API using Rest Template

Viewed 186

I have a third party API that returns an image as a response in png format.I'm using Rest template to call that API and get the response as Byte[] but I'm getting this exception

There was an unexpected error (type=Bad Request, status=400).JSON parse error: Can not deserialize instance of java.lang.Byte[] out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.Byte[] out of START_OBJECT token at [Source: java.io.PushbackInputStream@7c9dac50; line: 1, column: 1]

I have written the following code to get the image using the rest template

HttpHeaders headers = new HttpHeaders();
headers.add("Accept", "*/*");
headers.set("Authorization","Bearer "+bearerToken);
headers.setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM));
HttpEntity<String> entity = new HttpEntity<String>(headers);
ResponseEntity<Byte[]> response = restTemplate.exchange(endPoint,HttpMethod.GET,entity,Byte[].class);

How to get an image from an API using the rest template in java?

1 Answers

Can you try this ?

ImageModel.java

import javax.persistence.*;
@Entity
@Table(name = "image_table")
public class ImageModel {
    public ImageModel() {
        super();
    }
    public ImageModel(String name, String type, byte[] picByte) {
        this.name = name;
        this.type = type;
        this.picByte = picByte;
    }
    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(name = "name")
    private String name;
    @Column(name = "type")
    private String type;
    //image bytes can have large lengths so we specify a value
    //which is more than the default length for picByte column
    @Column(name = "picByte", length = 1000)
    private byte[] picByte;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public byte[] getPicByte() {
        return picByte;
    }
    public void setPicByte(byte[] picByte) {
        this.picByte = picByte;
    }
}

ImageRepository.java

    import java.util.Optional;
    import org.springframework.data.jpa.repository.JpaRepository;
    import com.javainuse.model.ImageModel;
    public interface ImageRepository extends JpaRepository<ImageModel, Long> {
        Optional<ImageModel> findByName(String name);
    }

ImageUploadController.java


@RestController
@RequestMapping(path = "image")
public class ImageUploadController {
    @Autowired
    ImageRepository imageRepository;
    
    @GetMapping(path = { "/get/{imageName}" })
    public ImageModel getImage(@PathVariable("imageName") String imageName) throws IOException {
        final Optional<ImageModel> retrievedImage = imageRepository.findByName(imageName);
        ImageModel img = new ImageModel(retrievedImage.get().getName(), retrievedImage.get().getType(),
                decompressBytes(retrievedImage.get().getPicByte()));
        return img;
    }
    // compress the image bytes before storing it in the database
    public static byte[] compressBytes(byte[] data) {
        Deflater deflater = new Deflater();
        deflater.setInput(data);
        deflater.finish();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
        byte[] buffer = new byte[1024];
        while (!deflater.finished()) {
            int count = deflater.deflate(buffer);
            outputStream.write(buffer, 0, count);
        }
        try {
            outputStream.close();
        } catch (IOException e) {
        }
        System.out.println("Compressed Image Byte Size - " + outputStream.toByteArray().length);
        return outputStream.toByteArray();
    }
}
Related