Home > Back-end >  Post request to external service with data in Springboot
Post request to external service with data in Springboot

Time:06-09

I need to send post request to external service with data. How can I achieve that in Springboot. For example - need to connect and send a request to endpoint a 10.20.30.111:30 with some data. Then that data will be tested and send back test result as response.

I am new to java and did some research but did not get any success.

CodePudding user response:

You can check HttpClient

URI uri = URI.create("10.20.30.111:30/endpoint");
HttpRequest req = HttpRequest.newBuilder().uri(uri).build();
HttpResponse<String> response = httpClient.send(req,HttpResponse.BodyHandlers.ofString());
String body = response.body();

If the response is json, you can convert the String response body to a custom object using JSONB.

Jsonb jsonb = JsonBuilder.create();
MyDataClass myDataObject = jsonb.fromJson(body, MyDataClass.class);

CodePudding user response:

Check the Feign Client: https://cloud.spring.io/spring-cloud-netflix/multi/multi_spring-cloud-feign.html

Your POST request will be implemented by an Interface like:

@FeignClient("stores")
public interface StoreClient {

@RequestMapping(method = RequestMethod.POST, value = "/stores/{storeId}", consumes = "application/json")
Store update(@PathVariable("storeId") Long storeId, Store store);
 }
  • Related