springboot使用RestTemplate以post方式发送json字符串参数

华凌
2023-12-01

pom依赖

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-web</artifactId>
</dependency>
import javax.annotation.Resource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class RestCommandLine{

    @Resource
    private RestTemplate restTemplate;

    public void run(String... args) throws Exception {

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);

        String content = "{ \"msgtype\": \"text\", \"text\": {\"content\": \"This is a test case.\"}, \"at\": {\"atMobiles\": [phone num], \"isAtAll\": false}}";

        HttpEntity<String> request = new HttpEntity<>(content, headers);

        String url = "https://oapi.dingtalk.com/robot/send?access_token=65eff73abfd26a3e5e11dc87c2c8bcbf359f15b65cd1d3bcb60443307fba675a1";
        ResponseEntity<String> postForEntity = restTemplate.postForEntity(url, request, String.class);

        String body = postForEntity.getBody();

        System.out.println(body);
    }

}
 类似资料: