Rest Template with multipart request - spring-boot

I need to replace the following Salesforce request in my Spring Boot application
--boundary_string
Content-Disposition: form-data; name="entity_content";
Content-Type: application/json
{
"ContentDocumentId" : "069D00000000so2",
"ReasonForChange" : "Marketing materials updated",
"PathOnClient" : "Q1 Sales Brochure.pdf"
}
--boundary_string
Content-Type: application/octet-stream
Content-Disposition: form-data; name="VersionData"; filename="Q1 Sales Brochure.pdf"
Binary data goes here.
--boundary_string--
I'm using Rest Template. Here my code:
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
headers.add(HttpHeaders.AUTHORIZATION, getAccessToken());
MultiValueMap<String, String> filePart = new LinkedMultiValueMap<>();
var contentDisposition = ContentDisposition
.builder("form-data")
.name("VersionData")
.filename(file.getOriginalFilename())
.build();
filePart.add(HttpHeaders.CONTENT_DISPOSITION, contentDisposition.toString());
HttpEntity<byte[]> fileEntity = new HttpEntity<>(file.getBytes());
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
var requestContent = RequestEntityContentDTO.builder().ContentDocumentId(accountSfid).build();
body.add("entity_content", requestContent);
body.add("VersionData", fileEntity);
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
ResponseEntity<String> response = restTemplate.postForEntity(baseUrl + "/services/data/v55.0/sobjects/ContentVersion" , requestEntity, String.class);
With this request, i always get error like my request has no binary part. Has anyone some advice to solve the problem?

Related

How to add file as Form data in Http request in spring boot

I'm writing test cases to a controller in spring boot which takes MultipartFile as RequestParam. In the test case method I'm using TestRestTemplate.exchange() to send the request to the controller. I'm not sure how to make the Headers correctly so that I can send the request.
The Postman curl looks like this:
curl --location --request POST 'localhost:9091/response/upload'
--form 'file=#"/home/adityak/Downloads/ClientLog_NEW.txt"'
For file uploading to any service or endpoint
private String testExchange(File file) {
//add file
LinkedMultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
params.add("file", new FileSystemResource(file));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity =
new HttpEntity<>(params, headers);
ResponseEntity<String> responseEntity = restTemplate.exchange(
"/upload-file",
HttpMethod.POST,
requestEntity,
String.class);
HttpStatus statusCode = responseEntity.getStatusCode();
if (statusCode == HttpStatus.ACCEPTED) {
result = responseEntity.getBody();
}
return result;
}

RestTemplate - 415 UNSUPPORTED_MEDIA_TYPE Error

I want to call a REST service from my application. I'm not passing any request to this call. But I can't figure out from where it comes from?
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("username", bonitaUsername);
map.add("password", bonitaPassword);
map.add("redirect", "false");
HttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter();
HttpMessageConverter stringHttpMessageConverternew = new StringHttpMessageConverter();
List<HttpMessageConverter<?>> converters = new ArrayList<>();
converters.add(formHttpMessageConverter);
converters.add(stringHttpMessageConverternew);
restTemplate.setMessageConverters(converters);
HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(map, headers);
ResponseEntity<?> response = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
List<String> cookies = response.getHeaders().get("Set-Cookie");
String cookieString = "";
for (String cookie : cookies) {
System.out.println();
cookieString += cookie.split(";")[0] + "; ";
}
return cookieString;
This happens due to the mismatch of content types which passing to REST template. Please make sure to send the correct content type. Some times we are receiving JSON request but we need to send as another format.

Sending multipart requests using Spring Boot with specific header for every part

Postman request
As mentioned in image I would like to send content-type as application/json for a particular part of a multipart request in springboot application.
use MultipartBodyBuilder to build your request.
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
headers.add("add custome header", "header value");
MultipartBodyBuilder builder = new MultipartBodyBuilder();
builder.part("json_part", "").header("Content-Type", "application/json");
MultiValueMap<String, HttpEntity<?>> body = builder.build();
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity(body,
headers);
RestTemplate restTemplate = new RestTemplateBuilder().build();
ResponseEntity<String> postResponse = restTemplate
.postForEntity("yoururl", requestEntity, String.class);

Why set an "Accept" in Spring Resttemplate is invalid

Here is my code:
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.TEXT_HTML));
headers.setContentType(MediaType.TEXT_XML);
HttpEntity<String> entity = new HttpEntity<>(src, headers);
ResponseEntity<String> responseEntity = restTemplate.exchange(requestUrl, HttpMethod.POST, entity, String.class);
System.out.println(responseEntity);
why my log file print accept is : text/plain, application/json, application/*+json, /

Spring RestTemplate exchange return 204 and in postman 200

I'm turning around since this morning , i've this method that return NO_CONTENT (204) in Java, but when i execute the same URL in postman i got Content (200)
String encodedCredentials = getEncodedCredentials(deviceConfigurationInstance);
RestTemplate restTemplate = getRestTemplate(url, deviceConfigurationInstance);
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + encodedCredentials);
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Accept", "*/*");
HttpEntity<String> request = new HttpEntity<String>(headers);
ResponseEntity<T> response = restTemplate.exchange(url, HttpMethod.GET, request, retType);
return response;
I've add the credential in postman also
What i've forgot in Java ?
Note : retType has Class<T> as type

Resources