restTemplate 发送post请求

时间:2025-03-21 09:39:18
        <!--jackson 依赖-->
        <dependency>
            <groupId></groupId>
            <artifactId>jackson-core</artifactId>
        </dependency>

        <dependency>
            <groupId></groupId>
            <artifactId>jackson-annotations</artifactId>
        </dependency>

        <dependency>
            <groupId></groupId>
            <artifactId>jackson-dataformat-xml</artifactId>
        </dependency>

package ;

import ;
import ;
import ;
import .slf4j.Slf4j;
import .*;
import ;

import ;

/**
 * User: ldj
 * Date: 2022/3/25
 * Time: 1:30
 * Description: restTemplate
 */
@Slf4j
public class RestTemplateDemo {
    public static void main(String[] args) throws JsonProcessingException {

        String url = "http://locahost:8080/test";
        
        RestTemplate restTemplate = new RestTemplate();

        HttpHeaders headers = new HttpHeaders();
        MediaType type = ("application/json; charset=UTF-8");
        (type);
        ("Accept", MediaType.APPLICATION_JSON.toString());
        
        ArrayList<Object> similarList = new ArrayList<>();
        ("1");
        ("2");
        ("3");

        JSONObject requestMap = new JSONObject();
        ("name", "ldj");
        ("age", "15");
        ("similarList",similarList);

        HttpEntity<JSONObject> entity = new HttpEntity<>(requestMap, headers);

        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String similarJSON = (requestMap);
            ("similarJSON:{}",similarJSON);
        } catch (Exception e) {
            ();
        }

        //使用JSONObject,不需要创建实体类VO来接受返参,缺点是别人不知道里面有哪些字段,即不知道有那些key
        JSONObject body1 = (url, entity, );
        ("body1:{}",(body1));

        ResponseEntity<JSONObject> responseEntity = (url, requestMap, );
        JSONObject body2 = (); //响应体
        HttpStatus statusCode = (); //状态码
        HttpHeaders headers1 = ();//获取到头信息
    }
}
package ;

import ;
import .slf4j.Slf4j;
import ;
import ;
import ;
import ;
import .*;
import .;
import ;
import ;
import ;

import ;
import ;
import ;
import ;
import ;

/**
 * @Author: ldj
 * @Date: 2022/06/24/11:32
 * @Description:
 */

@Slf4j
@RunWith()
@AutoConfigureMockMvc
@SpringBootTest
public class RestTemplateTest {

    @Autowired
    private RestTemplate restTemplate;

    public void test() {
        String url = "http://localhost:8089/UserController/test";

        Map<String, Object> requestMap = new HashMap<>();
        ("id", 145515555);
        ("name", "ldj");

        UriComponentsBuilder uriComponentsBuilder = (url);

        //拼接url参数 "http://localhost:8089/UserController/test?id=145515555&name=ldj"
        (uriComponentsBuilder::queryParam);

        URI uri = ().encode(StandardCharsets.UTF_8).toUri();

        //1.请求头
        HttpHeaders httpHeaders = new HttpHeaders();
        //((MediaType.APPLICATION_JSON_UTF8_VALUE));
        (("application/json; charset=UTF-8"));
        ("Accept", MediaType.APPLICATION_JSON.toString());

        //2.请求体
        HttpEntity<Void> httpEntity = new HttpEntity<>(null, httpHeaders);

        //3.响应体
        ResponseEntity<UserDTO> responseEntity = null;

        //4.发送get请求
        try {
            responseEntity = ((), , httpEntity, );
        } catch (RestClientException e) {
            ("[RestTemplateTest-test] http request error", e);
        }
        
        //5.数据处理
        if ((responseEntity)) {
            UserDTO body = ();
            if ((body)) {
                ("返回错误的响应的状态码");
            } else {
                String status = ();
                if (!("200", status)) {
                    ("返回错误的响应的状态码");
                }

                //数据进行业务处理 略
            }
        }
        
        //===============================================================================   
        //4.发送post请求
        RequestEntity<Map<String,Object>> requestEntity = RequestEntity
                .post(uri)
                .header("Accept", MediaType.APPLICATION_JSON.toString())
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON)
                .body(new LinkedMultiValueMap<>()); //也可以是DTO

        try {
            responseEntity = (requestEntity,);
        } catch (RestClientException e) {
            ("[RestTemplateTest-test] http request error", e);
        }
    }
}

后续补充:向阿里云发送post请求获取短信验证码测试

 配置restTemplate   

package ;

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

/**
 * User: ldj
 * Date: 2022/9/1
 * Time: 5:00
 * Description: No Description
 */
@RefreshScope //动态加载配置文件(可不加)
@Configuration
public class RestTemplateConfig {

    //连接超时时间,当配置文件没设定时间时,默认6000ms
    @Value("${:6000}")
    private Integer connectTimeout;

    //读取超时时间,当配置文件没设定时间时,默认6000ms
    @Value("${:6000}")
    private Integer readTimeout;

    @Bean
    //@LoadBalanced //客户端对服务器的负载均衡
    public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
        return new RestTemplate(factory);
    }

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        (readTimeout);
        (connectTimeout);
        return factory;
    }
}

配置Jackson序列化与反序列化规则

package ;

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import .Jackson2ObjectMapperBuilder;

/**
 * User: ldj
 * Date: 2022/7/23
 * Time: 20:50
 * Description: No Description
 */

@Configuration
public class JacksonConfig {

    @Bean
    @Primary
    @ConditionalOnMissingBean()
    public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder)
    {
        ObjectMapper objectMapper = (false).build();
        SimpleModule simpleModule = new SimpleModule();
        //Long -> String 解决返回前端id是Long类型精度降低,后位数变成0 配置注解 @JsonSerialize(using = )使用
        (, );
        (simpleModule);

        //  默认
        // Include.NON_DEFAULT 属性为默认值不序列化
        // Include.NON_EMPTY 属性为 空("") 或者为 NULL 都不序列化,忽略该字段
        // Include.NON_NULL  属性为NULL 不序列化
        (.NON_EMPTY);

        // 允许出现单引号
        (.ALLOW_SINGLE_QUOTES, true);
        return objectMapper;
    }
}

如果报错:: No instances available for

at

@LoadBalanced 的作用是负载均衡,使用ip地址访问,无法起到负载均衡的作用,因为每次都是调用同一个服务 ;注释掉配置类//@LoadBalanced 


import ;
import ;
import ;
import ;
import ;
import .slf4j.Slf4j;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import .;
import ;
import ;
import ;
import ;
import ;

import ;
import ;

@Slf4j
@Import(value = {, })
@RunWith()
@SpringBootTest
public class ThirdPartyApplicationTests {
    
    @Autowired
    private RestTemplate restTemplate;


    @Autowired
    private ObjectMapper objectMapper;
    
    @Test
    public void smsTest() {
        //4.发送post请求
        String url = "/data/send_sms";
        String appCode = "APPCODE 65ed5499417944f1ad101a12014a80c9";
        UriComponentsBuilder uriComponentsBuilder = (url);
        URI uri = ().encode(StandardCharsets.UTF_8).toUri();

        //1.请求头
        HttpHeaders httpHeaders = new HttpHeaders();
        ("Authorization", appCode);
        ((MediaType.APPLICATION_FORM_URLENCODED_VALUE));

        MultiValueMap<String, String> requestMap = new LinkedMultiValueMap<>();
        ("content", "code:6666");
        ("phone_number", "填写真正的手机号码");
        ("template_id", "TPL_0000");

        RequestEntity<MultiValueMap<String, String>> requestEntity = RequestEntity
                .post(uri)
                .headers(httpHeaders)
                .body(requestMap);

        ResponseEntity<Response> responseEntity;
        try {
            responseEntity = (requestEntity, );
            //((()).toString());
            ((()));
        } catch (RestClientException e) {
            ("[RestTemplateTest-test] http request error", e);
        }

    }

    @Data
    //局部起作用注解,JacksonConfig是全局起作用,本测试不做全局配置,使用一个注解就可以
    @JsonInclude(value= .NON_NULL)
    public static class Response {

        private String status;

        private String request_id;

        private String reason;
    }
    
}