gpt4 book ai didi

jersey - 使用 Jersey 客户端设置 "Origin"和 "Access-Control-Request-Method" header

转载 作者:行者123 更新时间:2023-12-04 13:07:19 26 4
gpt4 key购买 nike

Jersey 客户端没有为我设置“原点” header ,我想知道我是否遗漏了什么。

String origin="http://www.localhost.com";
ClientResponse response= webResourceBuilder("my/endpoint")
.header( "origin" , origin)
.header("Access-Control-Request-Method", "POST")
.header("xorigin", origin)
.header("whatever", "test")
.accept("application/xml")
.get(ClientResponse.class);

当我在运行时检查服务器端的请求 header 时,我找到了“xorigin”和“whatever” header ,但没有找到“origin”和“Access-Control-Request-Method”

如何设置这些标题?

最佳答案

默认 Jersey 客户端使用 HttpURLConnection向服务器发送请求。 HttpUrlConnection限制在请求中发送的某些 header ,请参阅:

/*
* 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

    它禁止从请求中删除受限制的 header 。
  • 使用 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);
  • 关于jersey - 使用 Jersey 客户端设置 "Origin"和 "Access-Control-Request-Method" header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13255051/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com