作者使用的是RestTemplate来发送Http请求

关键代码

      将请求的接口所需数据放入Map中本次以业务环境是模拟发送验证码,消息随需求而定。

        String checkCode = runNumber();
        if(baseService.checkNameAndPhone(reqDTO.getUserName(),reqDTO.getUserPhone())) {
            MultiValueMap<String, String> jsonMap = new LinkedMultiValueMap();
            jsonMap.add("键", "值");
            jsonMap.add("键", "值");
            jsonMap.add("键", "值");
            jsonMap.add("验证码内容", "【" + baseMessages.getCompany() + "】验证码是:" + checkCode + ","+ baseMessages.getAging() +"分钟内有效,如非本人操作,请忽略此短信。");
            jsonMap.add("手机号", reqDTO.getUserPhone());
            HttpRespone hr = sendMessag(jsonMap, "请求接口的访问路径");
            Boolean temp = false;
            if (hr.getResult().hashCode() == "0".hashCode()) {
                 temp = baseService.updateCode(reqDTO.getUserName(), reqDTO.getUserPhone(), checkCode, new Date());
            }
            if(temp == false){
                return failure("验证发送失败!");
            }
            return success("发送成功!");
        }
        return failure("用户或者手机错误!");

请求信息的处理,并设置HTTP 消息实体类型为x-www-form-urlencoded

      请求类型请根据所发送请求接口所要求的实体类型来定,本方法仅针对请求对象接受Json数据为前提。

 public HttpRespone sendMessag(MultiValueMap<String, String> jsonMap, String url) throws URISyntaxException {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        //System.out.println(jsonMap.size());
        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<MultiValueMap<String, String>>(jsonMap, headers);
        String strbody=restTemplate.exchange(url, HttpMethod.POST, httpEntity,String.class).getBody();
        HttpRespone date= JSONObject.parseObject(strbody, HttpRespone.class);
        return date;
    }

回执的映射类

      根据所返回的参数来设计该对象,前提得是其返回的是Json数据

package com.yf.exam.modules.sys.user.dto;

import lombok.Data;
import lombok.ToString;

/**
 * @author :班奈
 * @version 1.0
 * @date 2022/1/13 22:37
 */
@Data
@ToString
public class HttpRespone {
    public String msg;
    public String code;
    public String content;
}

RestTemplate 配置类

/**
 * @author :班奈
 * @version 1.0
 * @date 2022/1/13 20:12
 */
@Configuration
public class RestTemplateConfig {

    @Autowired
    private ApplicationValues appValues;

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate(simpleClientHttpRequestFactory());
    }

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(150000);
        factory.setReadTimeout(5000);
        return factory;
    }

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐