HTTP请求通用Restful风格工具类

HTTP请求通用Restful风格工具类

一、创建测试方法

/**
 * 模拟请求his测试类
 *
 * @Author: DengChang
 * @Date: 2020/8/25 11:07
 */
@RestController
@RequestMapping("rest")
@Api (tags = "测试接口")
public class HttpRestController {

    @Autowired
    private HttpRestUtil httpRestUtil;

    /**
     * 登录质控测试post请求
     *
     * @return
     */
    @ApiOperation (value = "登录质控测试post请求")
    @PostMapping("postLogin")
    public HisResponse postLogin() {
        String url = "http://192.168.21.12:8484/api/login?username=admin&pwd=admin";
        HisResponse response = httpRestUtil.request(null);
        return response;
    }

    @ApiOperation (value = "调质控添加用户的请求")
    @PostMapping("postAddUser")
    public HisResponse postAddUser() {
        String url = "http://192.168.21.12:8484/api/user/addUser";
        //两种传参都行,推荐第一种
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username", "dc0825");
        jsonObject.put("pwd", "123456");
        jsonObject.put("isMaster", 0);
        jsonObject.put("organizationId", 0);
        jsonObject.put("status", 1);
        jsonObject.put("type", 1);

        /*String params="{\n" +
                "  \"isMaster\": 0,\n" +
                "  \"organizationId\": 0,\n" +
                "  \"pwd\": \"123456\",\n" +
                "  \"status\": 0,\n" +
                "  \"type\": 1,\n" +
                "  \"userName\": \"dc1111\"\n" +
                "}";*/

        HisResponse request = httpRestUtil.request (jsonObject.toJSONString ());
        return request;
    }
}

二、Http请求工具类

/**
 * Http请求工具类
 *
 * @Author: DengChang
 * @Date: 2020/8/25 10:09
 */
@Component
public class HttpRestUtil {

    private static Logger logger = LoggerFactory.getLogger(HttpRestUtil.class);

    /**his请求地址*/
    @Value ("${his.url}")
    private String URL;

    @Autowired
    private RestTemplate restTemplate;
    /**
     * 通用请求方法,可更具情况是否带参数
     * @param params,请求数据,格式为json格式的数据 body-raw-json,用作post请求
     * @return
     */
    public HisResponse request(String params) {
        //header参数
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);

        //TODO  此处做成全局的 his那边登录时如何传头信息再商量
        headers.add(BaseConstants.CACHE_REDIS_KEY.UA_SESSION_ID, SpringContextUtil.getBean(SessionUtil.class).getUserSessionId());
        HttpEntity<String> request = new HttpEntity<>(params, headers);

        //TODO  可以改成his接口返回类
        ResponseEntity<String> response = null;
        long start = System.currentTimeMillis();
        logger.info("request his start----------------------{}millis",start);
        try {
            response = restTemplate.exchange(URL, HttpMethod.POST, request, String.class);
        }
        catch (Exception e) {
            logger.error("request his failed----------------------{}",e.getMessage(),e);
            throw new RuntimeException ("调用失败:"+e);
        }
        long end = System.currentTimeMillis();
        logger.info ("request end----------------------{}millis,process:{}millis", end, end - start);
        logger.info("post data----------------------{}", response.getBody());
        return JSON.parseObject (response.getBody (), HisResponse.class);
    }
 }

三、restTemplate 配置类

/**
 * restTemplate 配置类
 *
 * @Author: DengChang
 * @Date: 2020/8/25 14:36
 */
@Configuration
public class RestTemplateConfig {

    @Value ("${timeout.connect}")
    private Integer connect;

    @Value("${timeout.read}")
    private Integer read;

    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
        RestTemplate restTemplate = new RestTemplate(factory);
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
            @Override
            public void handleError(ClientHttpResponse response) throws IOException {
                if (response.getRawStatusCode() != HttpStatus.UNAUTHORIZED.value()) {
                    super.handleError(response);
                }
            }
        });
        StringHttpMessageConverter converter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
        restTemplate.setMessageConverters(Collections.singletonList(converter));
        return restTemplate;
    }

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(connect);
        factory.setReadTimeout(read);
        factory.setOutputStreaming(false);
        return factory;
    }

}

欢迎大神来指点

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值