Dynamic url - Feign Client

29 Views Asked by At

I need to make post requests to an endpoint that i do not know for sure from the start and only after i receive the payload for example:

messageBody.getCallbackUri()

Do you know a solution in java spring because i tried with fiegn client but it requires a base url but i need to set that url based on payload i recieve:

@Slf4j
@Service
@RequiredArgsConstructor
public class NotifyService {

  private final FClient fClient;

  public void notify(
      String postPayload, OrderDto messageBody, int numberOfAttempts) {
    log.info(
        "Posting payload "
            + postRequestPayload
            + "to"
            + messageBody.getCallbackUri()
            + "..."
            + "attempting "
            + numberOfAttempts
            + " times");
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    for (int i = 1; i <= numberOfAttempts; i++) {
      try {
        log.info("Trying Post request, attempt number-" + i);
        ResponseEntity<String> response =
            fClient.postCallback(messageBody.getUri(), postPayload, headers);
        log.info("Attempt " + i + ": Response code: " + response.getStatusCodeValue());

        if (response.getStatusCode().is2xxSuccessful()) {
          break; // Break the loop if successful response
        }
      } catch (RestClientException restClientException) {
        log.error("Post request unsuccessfully", restClientException);
      }
    }
  }
}

@FeignClient(name = "Client", url = "your-service-url")
interface FClient {

  @PostMapping
  ResponseEntity<String> postCallback(
      @RequestParam("Uri") String callbackUri,
      @RequestBody String postPayload,
      @RequestHeader HttpHeaders headers)
}

See the url is apppended with your-service-url but i need to do a post only to messageBody.getUri()

Thanks

1

There are 1 best solutions below

1
user23212569 On

you can use a frame which name 'forest' you can search it in maven repository. for example

<dependency>
    <groupId>com.dtflys.forest</groupId>
    <artifactId>forest-spring-boot-starter</artifactId>
    <version>1.5.28</version>
</dependency>

docs on this link https://forest.dtflyx.com/

You can use the following code as a demo

/
** 
 * 若全局变量中已定义 baseUrl 和 accept,
 * 便会将全局变量中的值绑定到 @BaseRequest 的属性中
 */
@BaseRequest(
    baseURL = "${baseUrl}",     // 默认域名
    headers = {
        "Accept:${accept}"      // 默认请求头
    }
)
public interface MyClient {

    // 方法的URL的域名将会引用全局变量中定义的 baseUrl
    @Get("{url1}")     
    String send1(@Query("url1") String username),@Query("username") String username);

 
}