1、带有头部信息的get请求
//api访问链接 String host = aliWuliuConfig.getHost(); //API访问后缀 String path = aliWuliuConfig.getPath()+"?type={type}&no={no}"; String url = host + path; //替换成自己的阿里云appcode String appcode = aliWuliuConfig.getAppcode(); //headers HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.add("Authorization", "APPCODE " + appcode); //body Map<String, Object> requestBody = new HashMap<String, Object>(); requestBody.put("no", no); requestBody.put("type",kdnCode); //HttpEntity HttpEntity<MultiValueMap> requestEntity = new HttpEntity<>(null, requestHeaders); //请求 ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class, requestBody);
2、带有头部信息的为post请求
HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>(); map.add("email", "[email protected]"); HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers); ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class );
3、普通get请求
String url = pmsServiceConfig.getDomainWithProtocol() + "/api/java_api/getLogistics"; try { Map<String, String> param = new HashMap<>(1); JSONObject res = restTemplate.postForEntity(url, param, JSONObject.class).getBody(); if (res.getInteger("code") <= 0) { throw BusinessException.of(ErrorMsgEnum.E6); } return res.getJSONArray("data").toJavaList(LogisticsInfo.class); } catch (HttpClientErrorException e) { log.error("pms调用失败:", e); throw BusinessException.of(ErrorMsgEnum.E6); }
4、普通post请求
String url = pmsServiceConfig.getDomainWithProtocol() + "/api/java_api/web_list"; Map<String, Object> param = new HashMap<>(1); param.put("uids", uidList); try { JSONObject res = restTemplate.postForEntity(url, param, JSONObject.class).getBody(); if (res.getInteger("code") <= 0) { throw BusinessException.of(ErrorMsgEnum.E6); } return res.getJSONArray("data").toJavaList(PMSUserWebInfo.class); } catch (HttpClientErrorException e) { log.error("pms调用失败:", e); throw BusinessException.of(ErrorMsgEnum.E6); }
标签:HttpEntity,String,url,spring,RestTemplate,param,api,使用,new From: https://www.cnblogs.com/anquing/p/17637776.html