Reputation: 743
I am fetching the byte array using Spring Framework RestTemplate
.
But I also need to fetch the media type of the fetched result.
The media type of this byte array can be of any type.
The code used now for fetching bytes is below.
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.valueOf("application/pdf")));
ResponseEntity<byte[]> result = restTemp.exchange(
url,
HttpMethod.GET,
entity,
byte[].class,
documentId
);
The above code will fetch only PDF content type.
So I have the following questions:
Any suggestions are welcome.
Upvotes: 17
Views: 33983
Reputation: 439
RestTemplate restCall = new RestTemplate();
String uri = ""; //Your URL
byte[] content = restCall.getForObject(uri, byte[].class);
This code uses the RestTemplate class to make an HTTP GET request to a specified URL. The uri variable holds the URL, and getForObject(uri, byte[].class) fetches the content as a byte[] (binary data). The response is stored in the content variable as a byte array. This approach is commonly used to download binary files, like images or PDFs, from a web service. The RestTemplate simplifies handling HTTP requests and responses in Spring applications.
Upvotes: 0
Reputation: 39261
Just not send the accept
header to not force the server to return that content-type
. This is the same as sending a wildcard */*
//HttpHeaders headers = new HttpHeaders();
//headers.setAccept(Collections.singletonList(MediaType.WILDCARD));
ResponseEntity<byte[]> result = restTemp.exchange(url, HttpMethod.GET, entity, byte[].class,documentId);
After this, extract the content-type
from the headers of the response
byte body[] = result.getBody();
MediaType contentType = result.getHeaders().getContentType();
Upvotes: 22
Reputation: 22432
You can set the MediaType
as application/octet-stream
, look at here
Upvotes: 1
Reputation: 196
You can store a media type in the HTTP headers and use - ResponseEntity.getHeaders(), for instance. or you can wrap byte array and media type into holder class.
Upvotes: 0