resttemp发送httppost请求和form表单请求

form表单请求

/**
 * <p>
 * cabala 异步进行客户表信息同步
 * </p>
 *
 * @author jindalong
 * @since 2021-01-25
 */

@Slf4j
@Service
public class NotifiCustomerServiceImpl implements NotifiCustomerService {

    @Value("${customer.cabalaurl:}")
    private String url;

    @Override
    @Async
    public String insertCustomer(String requestString){
        System.out.println("同步cabala信息");
        String sendUrl = url ;
        RestTemplate client = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        //提交方式都是表单提交
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        //封装参数,千万不要替换为Map与HashMap,否则参数无法传递
        //MultiValueMap<String, String> params= JSON.parseObject(requestString,LinkedMultiValueMap.class);
        Map<String, Object> map= JSON.parseObject(requestString, Map.class);

        MultiValueMap params = new LinkedMultiValueMap();
        for(Iterator<Map.Entry<String, Object>> itr = map.entrySet().iterator(); itr.hasNext();){
            Map.Entry<String, Object> entry = itr.next();
            String key = entry.getKey();
            String value = entry.getValue()+"";
            params.put(key, new ArrayList(Arrays.asList(value)));
        }

        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers);
        //  执行HTTP请求
        System.out.println("url:"+sendUrl+"参数:"+JSON.toJSONString(requestEntity));
        ResponseEntity<String> response = client.exchange(sendUrl, HttpMethod.POST, requestEntity, String.class);
        //  输出结果
        System.out.println(response.getBody());
        return  "success" ;
    }

}

常规post请求


    @Service
    public class NotificationManageSendImpl implements NotificationManageSend {

        RestTemplate restTemplate = new RestTemplate();

        @Value("${url}")
        private String url;
        @Value("${email}")
        private String email;
        @Value("${message}")
        private String message;

        @Override
        @Async
        public String sendEmail(String requestString){
            String sendEmailUrl = url + email;
            restTemplate.getMessageConverters().set(1,new StringHttpMessageConverter(StandardCharsets.UTF_8));
            return restTemplate.postForObject(sendEmailUrl, requestString,String.class);
        }

猜你喜欢

转载自blog.csdn.net/qq_44691484/article/details/114788581
今日推荐