uploading multipart file to another server - spring-boot

I'm working on a spring boot / Angular 6 application, I want to upload files to a server, I followed this tutorial to upload a multipart file :" https://grokonez.com/spring-framework/spring-boot/angular-5-upload-get-multipartfile-to-from-spring-boot-server ". The upload of the file is on a folder in the application but now I want to upload the files to another server with URL; f.e : localhost:8081/uploads : it's another server, how can I do that?

You should do this with spring rest template and construct the body as below
MultiValueMap<String, Object> body
= new LinkedMultiValueMap<>();
body.add("files", getTestFile());
body.add("files", getTestFile());
body.add("files", getTestFile());
HttpEntity<MultiValueMap<String, Object>> requestEntity
= new HttpEntity<>(body, headers);
String serverUrl = "http://localhost:8081/upload/";
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate
.postForEntity(serverUrl, requestEntity, String.class);

Related

Upload to google drive using The files get uploaded, but, only in the root and are always named "Untitled"

I am trying to upload files to Google drive using a REST API
Everything is working fine, but files are uploading into Google Drive only in the root, and with "Untitled" as their name.
public class UploadTODrive {
public static DriveFiles UploadFileTODrive(String accessToken, MultipartFile files) throws IOException {
RestTemplate restTemplate = new RestTemplate();
String requestUri = "https://www.googleapis.com/upload/drive/v2/files";
System.out.println("ContentType==============: " + files.getContentType());
byte[] s=files.getBytes();
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", files.getContentType());
headers.setContentLength(0);
//headers.setContentType(MediaType.MULTIPART_FORM_DATA);
headers.add("Authorization", "Bearer " + accessToken);
HttpEntity<byte[]> requestEntity = new HttpEntity<>(s, headers);
ResponseEntity<String> response = restTemplate.exchange(requestUri, HttpMethod.POST, requestEntity,
String.class);
System.out.println("=====>Response: " + response);
Gson gson = new Gson();
DriveFiles driveFiles = gson.fromJson(response.getBody(), DriveFiles.class);
return driveFiles;
}
}
Files are uploaded to google drive in two parts.
The first part is the meta data of the file, this being the name and the mimetype most often and occasionally containing a parent directory.
The second part is the upload of the actual file stream.
It seams that you are uploading the file stream but you have forgotten to post the file metadata. This is posted in the body of your request
This is your HTTP Post request. You need to figure out how to add a post body to this. This is the documentation link to the writable fields that you can post insert#request-body
ResponseEntity<String> response = restTemplate.exchange(requestUri, HttpMethod.POST, requestEntity,
String.class);
Update
found this with a bit of googling
RESTRequest1.AddBody('{"title": "Capture.jpg"}', TRESTContentType.ctAPPLICATION_JSON);

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);

Sending a multipart request using RestTemplate

I want to make a multipart request to some external API (created using Spring Boot) but all I get is Required request part 'file' is not present.
I know the source code of the external API but I can't modify it. It looks like this:
#PostMapping("/upload")
public ResponseEntity handleFileUpload(#RequestParam("file") MultipartFile file){
return ResponseEntity.ok().build();
}
And from my application I create and send requests exactly like on the following snippet:
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> body
= new LinkedMultiValueMap<>();
body.add("file", "dupa".getBytes());
HttpEntity<MultiValueMap<String, Object>> requestEntity
= new HttpEntity<>(body, headers);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate
.postForEntity("http://api:8080/upload", requestEntity, String.class);
return response.getBody();
What's the reason it doesn't work? The above code rewritten using Apache HttpClient works like charm.
You basically have two options, the solution with byte array:
map.add("file", new ByteArrayResource(byteArrayContent) {
#Override
public String getFilename() {
return "yourFilename";
}
});
I remember having a problem with just adding a byte array, so you need to have a filename too and use ByteArrayResource.
Or adding a File:
map.add("file", new FileSystemResource(file));

How to send body content as raw JSON and not form-data in Spring Boot RestTemplate

I have a spring boot application and trying to invoke a rest service of another company by using RestTemplate.
The remote Rest Service required multiple header and body content as Raw JSON.
Here is the sample required body request :
{
"amount": "10000",
"destinationNumber": "365412"
}
But my request body generate like this :
{
amount= [10000],
destinationNumber= [365412]
}
I've done like this :
String BASE_URI = "http://server.com/sericeX";
RestTemplate template = new RestTemplate();
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
headers.add("Authorization","Some token");
headers.add("Content-Type", "application/json");
MultiValueMap<String, String> bodyParam = new LinkedMultiValueMap<>();
bodyParam.add("amount", request.getAmount());
bodyParam.add("destinationNumber",request.getDestinationNumber());
HttpEntity entity = new HttpEntity(bodyParam,headers);
ResponseEntity<TransferEntity> responseEntity = template.exchange(BASE_URI, HttpMethod.POST, entity,TransferEntity.class);
TransferEntity transferEntity = responseEntity.getBody();
Could you please tell me how can i generate body request as JSON ?
Thanks to #Alex Salauyou based on his comment using HashMap instead of MultiValueMap solved the problem. Here is the changes need to be done:
HashMap<String, String> bodyParam = new HashMap<>();
bodyParam.put("amount", request.getAmount());
bodyParam.put("destinationNumber",request.getDestinationNumber());

spring boot application periodic post request via resttemplate in json

Below is my spring boot code snippet to post json data to server url every few min to tell that I am alive and running(which loads my json input data to db). purpose of this post request is to update the status on application monitoring tool.
What could be the right approach to implment this behaviour in my spring boot app? Is their any decorator api to do such post request to url, every few miuntes through out the application.? how can I know the time of successful post request to do next post request ? Please help me. Thanks in advance.
RestTemplate restTemplate = new RestTemplate();
String url = "endpoint url";
String requestJson = "{\"I am alive\":\"App name?\"}";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(requestJson,headers);
String answer = restTemplate.postForObject(url, entity, String.class);
System.out.println(answer);
Why don't you use the #Scheduled annotation? This will seutes.nd your REST request every 3 minutes...
#Component
public class Heartbeater {
#Scheduled(fixedDelay = 180000)
public void heartbeat() {
// Your code is below...
RestTemplate restTemplate = new RestTemplate();
String url = "endpoint url";
String requestJson = "{\"I am alive\":\"App name?\"}";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(requestJson,headers);
String answer = restTemplate.postForObject(url, entity, String.class);
System.out.println(answer);
}

Resources