首页 > 代码库 > RestTemplate发送请求并携带header信息
RestTemplate发送请求并携带header信息
1、使用restTemplate的postForObject方法
注:目前没有发现发送携带header信息的getForObject方法。
HttpHeaders headers = new HttpHeaders();Enumeration<String> headerNames = request.getHeaderNames();while (headerNames.hasMoreElements()) { String key = (String) headerNames.nextElement(); String value = request.getHeader(key); headers.add(key, value);} String restStrResult = restTemplate.postForObject(url, /*携带header*/new HttpEntity<String>(headers), String.class,
/*携带parameter*/request.getParameterMap());
2、使用restTemplate
import java.util.Enumeration;import java.util.Map;import javax.servlet.ServletRequest;import javax.servlet.http.HttpServletRequest;import org.springframework.http.HttpEntity;import org.springframework.http.HttpHeaders;import org.springframework.http.HttpMethod;import org.springframework.http.ResponseEntity;import org.springframework.web.client.RestTemplate;public class RestTemplateUtil { private RestTemplate restTemplate; public void setRestTemplate(RestTemplate restTemplate) { this.restTemplate = restTemplate; } public String post(ServletRequest req, String url, Map<String, ?> params) { ResponseEntity<String> rss = request(req, url, HttpMethod.POST, params); return rss.getBody(); } public String get(ServletRequest req, String url, Map<String, ?> params) { ResponseEntity<String> rss = request(req, url, HttpMethod.GET, params); return rss.getBody(); } public String delete(ServletRequest req, String url, Map<String, ?> params) { ResponseEntity<String> rss = request(req, url, HttpMethod.DELETE, params); return rss.getBody(); } public String put(ServletRequest req, String url, Map<String, ?> params) { ResponseEntity<String> rss = request(req, url, HttpMethod.PUT, params); return rss.getBody(); } /** * @param req * @param url * @param method * @param params maybe null * @return */ private ResponseEntity<String> request(ServletRequest req, String url, HttpMethod method, Map<String, ?> params) { HttpServletRequest request = (HttpServletRequest) req; //获取header信息 HttpHeaders requestHeaders = new HttpHeaders(); Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String key = (String) headerNames.nextElement(); String value = request.getHeader(key); requestHeaders.add(key, value); } //获取parameter信息 if(params == null) { params = request.getParameterMap(); } HttpEntity<String> requestEntity = new HttpEntity<String>(null, requestHeaders); ResponseEntity<String> rss = restTemplate.exchange(url, method, requestEntity, String.class, params); return rss; }}
RestTemplate发送请求并携带header信息
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。