RestTemplate发送请求并携带header信息 RestTemplate post json格式带header信息
原文地址: http://www.cnblogs.com/hujunzheng/p/6018505.html
RestTemplate发送请求并携带header信息
v1、使用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());
v2、使用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;
}
}
v 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;
}
v4. 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();
}
v5.最强版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 post json格式带header信息的更多相关文章
- RestTemplate发送请求并携带header信息
1.使用restTemplate的postForObject方法 注:目前没有发现发送携带header信息的getForObject方法. HttpHeaders headers = new Http ...
- 发送请求时携带了参数,但是浏览器network没有显示的排错思路
发送请求时携带了参数,但是浏览器network没有显示的排错思路 不知道大家有没有遇到这样子的情况就是发送请求的时候明明携带了参数,但是浏览器的network中就是没有!请看下图和代码! 我发送请求用 ...
- 页面发送请求到后台报错“Empty or invalid anti forgery header token.”问题解决
在页面向后台发送请求时,报如上图的错误的解决办法: 在WebModule.cs类中的PreInitialize方法中加 Configuration.Modules.AbpWeb().AntiForge ...
- 【spring】RestTemplate发送请求,请求第三方接口 的几种请求方式POST,GET,DELETE,PUSH
org.springframework.web.client.RestTemplate 参考地址:http://www.cnblogs.com/UniqueColor/p/7123347.html G ...
- 【转】ajax发送请求时候为什么会报拒绝设置不安全的header
浏览器不允许用户手动设置敏感的Http header包括但不限于cookie.host.referer 为了安全,跨域XHR对象有一些限制: 不能使用 setRequestHeader() 设置自定义 ...
- curl发送请求时携带cookie-转载未验证
<?php header('Content-Type:text/html;charset=utf-8'); echo "<pre>"; function curl ...
- 使用jQuery解析JSON数据(由ajax发送请求到php文件处理数据返回json数据,然后解析json写入html中呈现)
在上一篇的Struts2之ajax初析中,我们得到了comments对象的JSON数据,在本篇中,我们将使用jQuery进行数据解析. 我们先以解析上例中的comments对象的JSON数据为例,然后 ...
- 导出文件,responseType设置了blob,实际返回了JSON格式的错误信息的处理方式
需求:导出文件 问题描述:由于后台直接返回的文件流,在请求下载的方法中将XHR 的 responseType 指定为 blob 或者 arraybuffer.但并不是每次的操作都是成功的,所以在接口错 ...
- RestTemplate的逆袭之路,从发送请求到负载均衡
上篇文章我们详细的介绍了RestTemplate发送请求的问题,熟悉Spring的小伙伴可能会发现:RestTemplate不就是Spring提供的一个发送请求的工具吗?它什么时候具有了实现客户端负载 ...
随机推荐
- net core体系-web应用程序-4net core2.0大白话带你入门-9asp.net core服务的生命周期
asp.net core服务的生命周期 Transient:每一次GetService都会创建一个新的实例 Scoped:在同一个Scope内只初始化一个实例 ,可以理解为( 每一个request ...
- js防止安卓手机软键盘弹出挤压页面导致变形的方法
5防止安卓手机软键盘弹出挤压页面导致变形的方法 输入框定位在底部,手机端打开,输入框聚焦后软键盘打开为什么会瞬间自动关闭呢? 先看看问题: 1.原来是这样的: 2.在苹果手机里面是正常的: 3.到了安 ...
- 三次Java实验整理汇报:
*第一节 eclipse操作,建Javaproject项目(可直接用中文名命名)->建包与类(名字相同) ->public static void main(String[] args){ ...
- JavaSE| 集合
集合 l Collection 层次结构中的根接口.Collection 表示一组对象,这些对象也称为 collection 的元素.一些 collection 允许有重复的元素,而另一些则不允许. ...
- CodeSignal 刷题 —— almostIncreasingSequence
Given a sequence of integers as an array, determine whether it is possible to obtain a strictly incr ...
- Selenium3详解(基本操作,定位方法)
如果想使用selenium驱动不同的浏览器,必须单独下载并设置不同的浏览器驱动. 基本操作: 刷新:refresh, 获取浏览器窗口大小:get_window_size 设置浏览器窗口大小:set_w ...
- 爬虫1 socket方式下载一张图片
import socket import re client = socket.socket() # 图片url img_url = 'https://img03.sogoucdn.com/app/a ...
- POJ 1056 IMMEDIATE DECODABILITY 【Trie树】
<题目链接> 题目大意:给你几段只包含0,1的序列,判断这几段序列中,是否存在至少一段序列是另一段序列的前缀. 解题分析: Trie树水题,只需要在每次插入字符串,并且在Trie树上创建节 ...
- Linux系统开发之路-中
4.Linux的安装(Windows环境下): 1)Windows环境需要借助虚拟机来安装Linux系统,这个推荐使用的软件是VMWare,官网能下载到的最新版本是Workstation Pro15. ...
- Alpha(10/10)
鐵鍋燉腯鱻 项目:小鱼记账 团队成员 项目燃尽图 冲刺情况描述 站立式会议照片 各成员情况 团队成员 学号 姓名 git地址 博客地址 031602240 许郁杨 (组长) https://githu ...