欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

RestTemplate发送HTTP请求

程序员文章站 2022-06-25 19:17:18
...

POST请求

带Head头

		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON);
		//jsonParam是参数,headers是head头
        HttpEntity<String> entity = new HttpEntity<>(jsonParam, headers);
        log.info("请求URL【{}】,入参【{}】", url,jsonParam);
        String resultStr = restTemplate.postForObject(url, entity, String.class);
        log.info("返回结果【{}】",resultStr);

GET请求

带Head头

GET请求带Head头,需要转为exchange方式来实现

		String url = http://127.0.0.1:8080/user/{123}
		HttpEntity<MsgListParamDto> entity = new HttpEntity<>(null,getHttpHeaders());
        url = assembleUrlParam(param,url);
        log.info("请求URL【{}】,入参【{}】", url,param.toString());
        //最后一个参数是参数变量,用于替换url地址中的变量
        ResponseEntity<String> resultEntity = restTemplate.exchange(url, HttpMethod.GET, entity, String.class, param.getUserId());
        log.info("返回HttpStatus【{}】,返回结果【{}】", resultEntity.getStatusCodeValue(),resultEntity.getBody());

GET请求把参数拼接到url中

    /**
     * 组装get请求参数到url
     * @param param 请求参数
     * @param url 请求路径
     * @return String 组装参数之后的请求路径
     */
    @NonNull
    private <T> String  assembleUrlParam(@NonNull T param, @NonNull String url) {
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
        Map<String,Object> paramMap = JSONObject.parseObject(JSONObject.toJSONString(param), Map.class);
        paramMap.forEach((k,v) ->  builder.queryParam(k,v));
        return builder.build().toString();
    }
相关标签: HTTP java