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;
}
}
3.restTemplate以json格式发送post请求
1.发送请求
public String _post(ServletRequest req, String url, Map<String, ?> params) {
HttpServletRequest request = (HttpServletRequest) req;
//拿到header信息
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String key = (String) headerNames.nextElement();
String value = request.getHeader(key);
requestHeaders.add(key, value);
}
net.sf.json.JSONObject jsonParams = net.sf.json.JSONObject.fromObject(params);
HttpEntity<net.sf.json.JSONObject> requestEntity = new HttpEntity<net.sf.json.JSONObject>(jsonParams, requestHeaders);
String result = restTemplate.postForObject(url, requestEntity, String.class);
return result;
}
2.接收处理
@RequestMapping("/xxx")
@ResponseBody
public String xxx(HttpServletRequest request) throws IOException { String jsonString = getBodyString(request.getReader()); JSONObject jbJsonObject = new JSONObject().fromObject(jsonString); User user = (User) JSONObject.toBean(jbJsonObject, User.class);
System.out.println(jbJsonObject);
System.out.println("id:" + user.getUserName());return null; } @RequestMapping("/xxx2")
@ResponseBody
public String xxx2(User user) throws IOException { System.out.println("---------------");
System.out.println(user.getUserName());
System.out.println(user.getPassWord());
System.out.println("---------------"); if (true) {
return "success";
} else {
return "fail";
} }
public String getBodyString(BufferedReader br) {
String inputLine;
String str = "";
try {
while ((inputLine = br.readLine()) != null) {
str += inputLine;
}
br.close();
} catch (IOException e) {
System.out.println("IOException: " + e);
}
return str;
}
4. RestTemplate 的两个 postForObject方法的使用
private static String post(String url, JSONObject params, MediaType mediaType) {
RestTemplate restTemplate = new RestTemplate();
//拿到header信息
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(mediaType);
HttpEntity<JSONObject> requestEntity = (mediaType == MediaType.APPLICATION_JSON || mediaType == MediaType.APPLICATION_JSON_UTF8) ?
new HttpEntity<JSONObject>(params, requestHeaders) : new HttpEntity<JSONObject>(null, requestHeaders);
restTemplate.setErrorHandler(new ResponseErrorHandler() { @Override
public boolean hasError(ClientHttpResponse response) throws IOException {
return response.getStatusCode().value() != HttpServletResponse.SC_OK;
} @Override
public void handleError(ClientHttpResponse response) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(response.getBody()));
String str = null;
while((str = br.readLine()) != null) {
System.out.println(str);
}
}
});
String result = (mediaType == MediaType.APPLICATION_JSON || mediaType == MediaType.APPLICATION_JSON_UTF8) ?
restTemplate.postForObject(url, requestEntity, String.class) : restTemplate.postForObject(expandURL(url, params.keySet()), requestEntity, String.class, params);
return result;
} private static String expandURL(String url, Set<?> keys){
final Pattern QUERY_PARAM_PATTERN = Pattern.compile("([^&=]+)(=?)([^&]+)?");
Matcher mc = QUERY_PARAM_PATTERN.matcher(url);
StringBuilder sb = new StringBuilder(url);
if(mc.find()) {
sb.append("&");
} else {
sb.append("?");
} for(Object key : keys) {
sb.append(key).append("=").append("{").append(key).append("}").append("&");
}
return sb.deleteCharAt(sb.length()-1).toString();
}
5.最强版RestTemplateUtils
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.ResponseErrorHandler;
import org.springframework.web.client.RestTemplate; import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern; /**
* @Title: RestTemplateUtils.java
* @Prject: sensorsdata
* @Package: com.springboottest.sensorsdata.utils
* @Description: TODO
* @author: hujunzheng
* @date: 2017年4月20日 下午2:07:18
* @version: V1.0
*/
public class RestTemplateUtils { /**
* @ClassName: DefaultResponseErrorHandler
* @Description: TODO
* @author: hujunzheng
* @date: 2017年4月20日 下午2:15:27
*/
private static class DefaultResponseErrorHandler implements ResponseErrorHandler { @Override
public boolean hasError(ClientHttpResponse response) throws IOException {
return response.getStatusCode().value() != HttpServletResponse.SC_OK;
} @Override
public void handleError(ClientHttpResponse response) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(response.getBody()));
StringBuilder sb = new StringBuilder();
String str = null;
while ((str = br.readLine()) != null) {
sb.append(str);
}
try {
throw new Exception(sb.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
} /**
* @param url
* @param params
* @return
* @Title: get
* @author: hujunzheng
* @Description: TODO
* @return: String
*/
public static String get(String url, JSONObject params) {
RestTemplate restTemplate = new RestTemplate();
restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
String response = restTemplate.getForObject(expandURL(url, params.keySet()), String.class, params);
return response;
} /**
* @param url
* @param params
* @param mediaType
* @return
* @Title: post
* @author: hujunzheng
* @Description: 将参数都拼接在url之后
* @return: String
*/
public static String post(String url, JSONObject params, MediaType mediaType) {
RestTemplate restTemplate = new RestTemplate();
// 拿到header信息
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(mediaType);
HttpEntity<JSONObject> requestEntity = (mediaType == MediaType.APPLICATION_JSON
|| mediaType == MediaType.APPLICATION_JSON_UTF8) ? new HttpEntity<JSONObject>(params, requestHeaders)
: new HttpEntity<JSONObject>(null, requestHeaders);
restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
String result = (mediaType == MediaType.APPLICATION_JSON || mediaType == MediaType.APPLICATION_JSON_UTF8)
? restTemplate.postForObject(url, requestEntity, String.class)
: restTemplate.postForObject(expandURL(url, params.keySet()), requestEntity, String.class, params);
return result;
} /**
* @param url
* @param params
* @param mediaType
* @param clz
* @return
* @Title: post
* @author: hujunzheng
* @Description: 发送json或者form格式数据
* @return: String
*/
public static <T> T post(String url, JSONObject params, MediaType mediaType, Class<T> clz) {
RestTemplate restTemplate = new RestTemplate();
//这是为 MediaType.APPLICATION_FORM_URLENCODED 格式HttpEntity 数据 添加转换器
//还有就是,如果是APPLICATION_FORM_URLENCODED方式发送post请求,
//也可以直接HttpHeaders requestHeaders = new HttpHeaders(createMultiValueMap(params),true),就不用增加转换器了
restTemplate.getMessageConverters().add(new FormHttpMessageConverter());
// 设置header信息
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(mediaType); HttpEntity<?> requestEntity = (
mediaType == MediaType.APPLICATION_JSON
|| mediaType == MediaType.APPLICATION_JSON_UTF8)
? new HttpEntity<JSONObject>(params, requestHeaders)
: (mediaType == MediaType.APPLICATION_FORM_URLENCODED
? new HttpEntity<MultiValueMap>(createMultiValueMap(params), requestHeaders)
: new HttpEntity<>(null, requestHeaders)); restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
T result = (mediaType == MediaType.APPLICATION_JSON || mediaType == MediaType.APPLICATION_JSON_UTF8)
? restTemplate.postForObject(url, requestEntity, clz)
: restTemplate.postForObject(mediaType == MediaType.APPLICATION_FORM_URLENCODED
? url
: expandURL(url, params.keySet()), requestEntity, clz, params); return result;
} private static MultiValueMap<String, String> createMultiValueMap(JSONObject params) {
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
for(String key : params.keySet()) {
if(params.get(key) instanceof List) {
for(Iterator<String> it=((List<String>) params.get(key)).iterator(); it.hasNext(); ) {
String value = it.next();
map.add(key, value);
}
} else {
map.add(key, params.getString(key));
}
}
return map;
} /**
* @param url
* @param keys
* @return
* @Title: expandURL
* @author: hujunzheng
* @Description: TODO
* @return: String
*/
private static String expandURL(String url, Set<?> keys) {
final Pattern QUERY_PARAM_PATTERN = Pattern.compile("([^&=]+)(=?)([^&]+)?");
Matcher mc = QUERY_PARAM_PATTERN.matcher(url);
StringBuilder sb = new StringBuilder(url);
if (mc.find()) {
sb.append("&");
} else {
sb.append("?");
} for (Object key : keys) {
sb.append(key).append("=").append("{").append(key).append("}").append("&");
}
return sb.deleteCharAt(sb.length() - 1).toString();
}
}
RestTemplate发送请求并携带header信息的更多相关文章
- RestTemplate发送请求并携带header信息 RestTemplate post json格式带header信息
原文地址: http://www.cnblogs.com/hujunzheng/p/6018505.html RestTemplate发送请求并携带header信息 v1.使用restTempl ...
- 发送请求时携带了参数,但是浏览器network没有显示的排错思路
发送请求时携带了参数,但是浏览器network没有显示的排错思路 不知道大家有没有遇到这样子的情况就是发送请求的时候明明携带了参数,但是浏览器的network中就是没有!请看下图和代码! 我发送请求用 ...
- 如何利用fiddler篡改发送请求和截取服务器信息
一.断点的两种方式 1.before response:在request请求未到达服务器之前打断 2.after response:在服务器响应之后打断 二.全局打断 1.全局打断就是中断fiddle ...
- 【spring】RestTemplate发送请求,请求第三方接口 的几种请求方式POST,GET,DELETE,PUSH
org.springframework.web.client.RestTemplate 参考地址:http://www.cnblogs.com/UniqueColor/p/7123347.html G ...
- RestTemplate支持GET方法携带Body信息
首先必须声明: GET方法支持通过Body携带参数(HTTP1.1开始支持) 但是默认的RestTemplate是不支持滴!原因如下: RestTemplate支持通过setRequestFactor ...
- curl发送请求时携带cookie-转载未验证
<?php header('Content-Type:text/html;charset=utf-8'); echo "<pre>"; function curl ...
- RestTemplate的逆袭之路,从发送请求到负载均衡
上篇文章我们详细的介绍了RestTemplate发送请求的问题,熟悉Spring的小伙伴可能会发现:RestTemplate不就是Spring提供的一个发送请求的工具吗?它什么时候具有了实现客户端负载 ...
- 精讲RestTemplate第10篇-使用代理作为跳板发送请求
本文是精讲RestTemplate第10篇,前篇的blog访问地址如下: 精讲RestTemplate第1篇-在Spring或非Spring环境下如何使用 精讲RestTemplate第2篇-多种底层 ...
- axios添加了header信息后发送的get请求自动编程option请求了
axios添加了header信息后发送的get请求自动编程option请求了 webpack 代理转发 Provisional headers are shown 在Vue中如何使用axios跨域访问 ...
随机推荐
- 自定义基于 VLC 的视频播放器
前言(蛋疼的背景故事) 前段时间,接了一个小项目,有个需求是要在系统待机一段时间以后,循环播放 MV(类似于 Windows 系统的屏幕保护). 听到这个需求,我首先想到的是 MediaPlayer ...
- JS核心系列:浅谈原型对象和原型链
在Javascript中,万物皆对象,但对象也有区别,大致可以分为两类,即:普通对象(Object)和函数对象(Function). 一般而言,通过new Function产生的对象是函数对象,其他对 ...
- 漫扯:从polling到Websocket
Http被设计成了一个单向的通信的协议,即客户端发起一个request,然后服务器回应一个response.这让服务器很为恼火:我特么才是老大,我居然不能给小弟发消息... 轮询 老大发火了,小弟们自 ...
- jsp中出现onclick函数提示Cannot return from outside a function or method
在使用Myeclipse10部署完项目后,原先不出错的项目,会有红色的叉叉,JSP页面会提示onclick函数错误 Cannot return from outside a function or m ...
- JAVA for mac 的学习之路
要学习一门新技术,首先得下载相关的工具. 一 . 下载相关工具 1. 下载 jdk formac 下载地址为:http://www.oracle.com/technetwork/java/javase ...
- Android-armebi-v7a、arm64-v8a、armebi的坑
先来一波扫盲: armeabi:针对普通的或旧的arm v5 cpu armeabi-v7a:针对有浮点运算或高级扩展功能的arm v7 cpu(32位ARM设备) arm64-v8a:64位ARM设 ...
- 开源一个跨平台运行的服务插件 - TaskCore.MainForm
本次将要很大家分享的是一个跨平台运行的服务插件 - TaskCore.MainForm,此框架是使用.netcore来写的,现在netcore已经支持很多系统平台运行了,所以将以前的Task.Main ...
- [.NET] C# 知识回顾 - 委托 delegate (续)
C# 知识回顾 - 委托 delegate (续) [博主]反骨仔 [原文]http://www.cnblogs.com/liqingwen/p/6046171.html 序 上篇<C# 知识回 ...
- [.NET] 打造一个很简单的文档转换器 - 使用组件 Spire.Office
打造一个很简单的文档转换器 - 使用组件 Spire.Office [博主]反骨仔 [原文]http://www.cnblogs.com/liqingwen/p/6024827.html 序 之前,& ...
- SELECT INTO 和 INSERT INTO SELECT 两种表复制语句
Insert是T-sql中常用语句,Insert INTO table(field1,field2,...) values(value1,value2,...)这种形式的在应用程序开发中必不可少.但我 ...