How to Send an HTTP Header With Every Request With Spring RestTemplate
In Know Which Apps Are Hitting Your Web Service, I showed how to write a servlet filter that enforces the existence of a special HTTP request header.
From a client perspective, it would be nice to send this header automatically, instead of having to set the header manually with every request. This post shows how we can use Spring’s RestTemplate and ClientHttpRequestInterceptor to accomplish this.
First we need to implement a ClientHttpRequestInterceptor:
package com.myapp.connector;
import java.io.IOException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
public class XUserAgentInterceptor implements ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept(
HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
throws IOException {
HttpHeaders headers = request.getHeaders();
headers.add("X-User-Agent", "My App v2.1");
return execution.execute(request, body);
}
}
Now we need to configure our RestTemplate to use it. Here I’m using Spring’s Java-based configuration, but you can implement the same thing with the XML-based configuration too:
package com.myapp;
import java.util.Collections;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.web.client.RestTemplate;
import com.myapp.connector.XUserAgentInterceptor;
@Configuration
public class MyAppConfig {
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory());
restTemplate.setInterceptors(Collections.singletonList(new XUserAgentInterceptor()));
return restTemplate;
}
}
With this configuration, any requests you make through the RestTemplate will automatically carry the desired HTTP request header.
To learn how to set request timeouts automatically, see my post How to Set HTTP Request Timeouts With Spring RestTemplate.
http://springinpractice.com/2013/10/27/how-to-send-an-http-header-with-every-request-with-spring-resttemplate/
When creating a web service, it’s often useful to know which apps are hitting it. I don’t mean which users, but instead which apps. The reason is that you may want to coordinate with some other team on something. For example, maybe the team is being too aggressive about request retries, or maybe you want to alert the team to a change in the API. Whatever the reason, it’s good to know which apps are calling your service.
HTTP has a User-Agent header that can help here. One possible approach is to make that a required header. Unfortunately, this approach isn’t ideal. The problem is that HTTP client libraries usually set that header automatically. So if the client application forgets to set the header explicitly, you end up with user agents like Apache-HttpClient/release (java 1.5), which isn’t much help at all.
An approach I like better is to define a custom header and make it required. I use X-User-Agent, since it really is a user agent we’re talking about here.
Here’s how to implement this with a servlet filter. No Spring involved here at all; it’s just servlet stuff.
package com.myapp.web.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class XUserAgentFilter implements Filter {
private static final String X_USER_AGENT = "X-User-Agent";
private String errorJson;
public XUserAgentFilter() {
String message =
"HTTP header '" + X_USER_AGENT + "' is required. Please set it to your application name so we know " +
"who to contact if there's an issue.";
this.errorJson = "{ " + wrap("message") + " : " + wrap(message) + " }";
}
private String wrap(String s) { return "\"" + s + "\""; }
@Override
public void init(FilterConfig config) throws ServletException { }
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
if (httpRequest.getHeader(X_USER_AGENT) == null) {//不走chain.doFilter即结束
httpResponse.setStatus(422);
httpResponse.getWriter().println(errorJson);
} else {
chain.doFilter(request, response);
}
}
@Override
public void destroy() { }
}
Of course, you need to configure this filter and a filter mapping in your web.xml file.
In the next post I’ll show you how to set up your Spring RestTemplate to send the X-User-Agent header with each request automatically.
http://springinpractice.com/2013/10/25/know-which-apps-are-hitting-your-web-service/
In How to Send an HTTP Header With Every Request With Spring RestTemplate, we looked at how to send a given HTTP header automatically with every request. Here we’ll do something similar, which is to automatically apply a request timeout to every request.
Here’s the Java-based configuration for this technique:
package com.myapp;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
@Configuration
public class MyAppConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate(clientHttpRequestFactory());
}
private ClientHttpRequestFactory clientHttpRequestFactory() {
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
factory.setReadTimeout(2000);
factory.setConnectTimeout(2000);
return factory;
}
}
The XML-based configuration is this:
<bean class="org.springframework.web.client.RestTemplate">
<constructor-arg>
<bean class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory"
p:readTimeout="2000"
p:connectTimeout="2000" />
</constructor-arg>
</bean>
http://springinpractice.com/2013/10/27/how-to-set-http-request-timeouts-with-spring-resttemplate/
Basic Auth:
// Set the username and password for creating a Basic Auth request
HttpAuthentication authHeader = new HttpBasicAuthentication(username, password);
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setAuthorization(authHeader);
HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders); // Create a new RestTemplate instance
RestTemplate restTemplate = new RestTemplate(); // Add the String message converter
restTemplate.getMessageConverters().add(new StringHttpMessageConverter()); try {
// Make the HTTP GET request to the Basic Auth protected URL
ResponseEntity<Message> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
return response.getBody();
} catch (HttpClientErrorException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
// Handle 401 Unauthorized response
}
http://docs.spring.io/autorepo/docs/spring-android/1.0.x/reference/html/rest-template.html
https://www.cnblogs.com/rinack/p/7815064.html
How to Send an HTTP Header With Every Request With Spring RestTemplate的更多相关文章
- Spring RestTemplate: 比httpClient更优雅的Restful URL访问, java HttpPost with header
{ "Author": "tomcat and jerry", "url":"http://www.cnblogs.com/tom ...
- http header cache-control (request和response区别)
摘要:(1)网络服务会根据 request的header中的 cache-control策略设置response的cache-control策略 1 response cache-control 和 ...
- axios增加的自定义header,后端request取不到
1.拦截器配置 <!--拦截器--> <mvc:interceptors> <!-- web端增加头部接口 --> <mvc:interceptor> ...
- Using ASP.Net WebAPI with Web Forms
Asp.Net WebAPI is a framework for building RESTful HTTP services which can be used across a wide ran ...
- Secure Spring REST API using Basic Authentication
What is Basic Authentication? Traditional authentication approaches like login pages or session iden ...
- HTTP Header 入门详解
什么是HTTP Headers HTTP是"Hypertext Transfer Protocol"的所写,整个www都在使用这种协定,几乎你在流览器里看到的大部分内容都是通过ht ...
- mailsend - Send mail via SMTP protocol from command line
Introduction mailsend is a simple command line program to send mail via SMTP protocol. I used to sen ...
- libeXosip2(1-3) -- How-To send or update registrations.
How-To send or update registrations. The eXtented eXosip stack Initiate a registration To start a re ...
- PHP header() http各种状态码大全查询
PHP header()the function declaration: void header ( string string [, bool replace [, int http_respon ...
随机推荐
- Powerful Sleep(神奇的睡眠-睡眠生物钟的秘密:如何睡得更少却睡得更好)阅读笔记
睡眠机制 我们活着的时候,大脑会产生脑电波.脑电图仪器通过贴在人头上的一些电极读出脑电波的活动,然后把活动用图表显示出来. 睡眠过程可以分为5个过程,划分依据与大脑发出的脑电波类型. 当人清醒时,大脑 ...
- java.util.HashSet源码分析
public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, java. ...
- Java多线程(三) 多线程间的基本通信
多条线程在操作同一份数据的时候,一般需要程序去控制好变量.在多条线程同时运行的前提下控制变量,涉及到线程通信及变量保护等. 本博文主要总结:①线程是如何通信 ②如何保护线程变量 1.Java里的线程 ...
- MAF+WPF实现插件式应用程序框架
关于maf和wpf大家感兴趣的话可以去百度学习一下,下面展示一下成果: 登录界面 主界面:默认的是我的应用,表示已经下载到本地的应用. 辅助应用类似appstore功能,指示未下载或者需要升级的程序列 ...
- [原创] linux课堂-学习笔记-课程3.Linux目录结构介绍及内核与shell分析
一.目录说明 1.1 bin 一般用户,可执行的系统内置命令 1.2 sbin 系统管理员,可执行的系统内置命令 1.3 boot 启动文件目录,启动有关的文件都保存在此 1.4 dev 设备管理文件 ...
- 解决FPDF报错:FPDF error: Not a JPEG file / FPDF error: Not a PNG file
最近有个项目需要用到FPDF,但是输出的时候报错: FPDF error: Not a JPEG file: http://***/data/attachment/forum/201603/19/10 ...
- python学习之html从0开始(一)
<!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content ...
- Spark Streaming揭秘 Day9 从Receiver的设计到Spark框架的扩展
Spark Streaming揭秘 Day9 从Receiver的设计到Spark框架的扩展 Receiver是SparkStreaming的输入数据来源,从对Receiver整个生命周期的设计,我们 ...
- google其他入口地址
http://178.45.251.74/ http://64.233.166.51/ http://61.19.1.117/ http://64.233.166.42/ http://61.19.1 ...
- 《WPF程序设计指南》读书笔记——第8章 依赖属性
1.依赖属性的效果 一旦规定视觉树上一个对象的fontsize属性,那么属于他的节点之下的所有对象都会沿袭这个属性,然而如果某个子节点明确的设定了自己的fontsize,就不会沿袭父节点的fontsi ...