默认Jersey客户端使用HttpURLConnection发送请求到服务器。 HttpUrlConnection
限制一些头在请求被发送,请参阅:
/*
* Restrict setting of request headers through the public api
* consistent with JavaScript XMLHttpRequest2 with a few
* exceptions. Disallowed headers are silently ignored for
* backwards compatibility reasons rather than throwing a
* SecurityException. For example, some applets set the
* Host header since old JREs did not implement HTTP 1.1.
* Additionally, any header starting with Sec- is
* disallowed.
*
* The following headers are allowed for historical reasons:
*
* Accept-Charset, Accept-Encoding, Cookie, Cookie2, Date,
* Referer, TE, User-Agent, headers beginning with Proxy-.
*
* The following headers are allowed in a limited form:
*
* Connection: close
*
* See http://www.w3.org/TR/XMLHttpRequest2.
*/
private static final boolean allowRestrictedHeaders;
private static final Set<String> restrictedHeaderSet;
private static final String[] restrictedHeaders = {
/* Restricted by XMLHttpRequest2 */
//"Accept-Charset",
//"Accept-Encoding",
"Access-Control-Request-Headers",
"Access-Control-Request-Method",
"Connection", /* close is allowed */
"Content-Length",
//"Cookie",
//"Cookie2",
"Content-Transfer-Encoding",
//"Date",
//"Expect",
"Host",
"Keep-Alive",
"Origin",
// "Referer",
// "TE",
"Trailer",
"Transfer-Encoding",
"Upgrade",
//"User-Agent",
"Via"
};
你有两个选择如何处理这种情况:
在默认Jersey客户端,你需要设置系统属性
-Dsun.net.http.allowRestrictedHeaders=true
它抑制从请求中删除受限制的标题。
使用ApacheHttpClient/ApacheHttpClient4似乎没有这个限制。只需添加下面的一个依赖于你的项目:
<dependency>
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-apache-client</artifactId>
<version>1.15</version>
</dependency>
或
<dependency>
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-apache-client4</artifactId>
<version>1.15</version>
</dependency>
,然后创建你的客户,如:
ApacheHttpClient.create(com.sun.jersey.api.client.config.ClientConfig);
或
ApacheHttpClient4.create(com.sun.jersey.api.client.config.ClientConfig);
我能得到这个通过方法#1的工作。 其实我首选#2,但我一直收到“java.lang.IllegalStateException:使用无效SingleClientConnManager的:仍然分配的连接”的错误,尽管在下面的说明:http://java.net/jira/browse/JERSEY- 730 – SkP