How to post data to specific URL using WebClient in C#

后端 未结 8 1542
深忆病人
深忆病人 2020-11-22 07:12

I need to use \"HTTP Post\" with WebClient to post some data to a specific URL I have.

Now, I know this can be accomplished with WebRequest but for some reasons I wa

8条回答
  •  长发绾君心
    2020-11-22 08:02

    Here is the crisp answer:

    public String sendSMS(String phone, String token) {
        WebClient webClient = WebClient.create(smsServiceUrl);
    
        SMSRequest smsRequest = new SMSRequest();
        smsRequest.setMessage(token);
        smsRequest.setPhoneNo(phone);
        smsRequest.setTokenId(smsServiceTokenId);
    
        Mono response = webClient.post()
              .uri(smsServiceEndpoint)
              .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
              .body(Mono.just(smsRequest), SMSRequest.class)
              .retrieve().bodyToMono(String.class);
    
        String deliveryResponse = response.block();
        if (deliveryResponse.equalsIgnoreCase("success")) {
          return deliveryResponse;
        }
        return null;
    }
    

提交回复
热议问题