Java Jersey 2.x:如何在 RESTful 客户端上添加标题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32532959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jersey 2.x: How to add Headers on RESTful Client
提问by Joshua Kissoon
I've already looked at How to add Headers on RESTful call using Jersey Client API, however this is for Jersey 1.x.
我已经看过如何使用 Jersey 客户端 API 在 RESTful 调用中添加标题,但是这是针对 Jersey 1.x 的。
How do I set a header value (such as an authorization token) in Jersey 2.21?
如何在 Jersey 2.21 中设置标头值(例如授权令牌)?
Here is the code I'm using:
这是我正在使用的代码:
public static String POST(final String url, final HashMap<String, String> params)
{
ClientConfig config = new ClientConfig();
Client client = ClientBuilder.newClient(config);
WebTarget target = client.target(url);
String data = new Gson().toJson(params);
Entity json = Entity.entity(data, MediaType.APPLICATION_JSON_TYPE);
Invocation.Builder builder = target.request(MediaType.APPLICATION_JSON_TYPE);
return builder.post(json, String.class);
}
采纳答案by rgettman
In Jersey 2.0+, you can register a custom implementation of ClientRequestFilter
that can manipulate the headersin the request that the Client API will send out.
在 Jersey 2.0+ 中,您可以注册一个自定义实现,ClientRequestFilter
该实现可以操作客户端 API 将发出的请求中的标头。
You can manipulate the headers via the ClientRequestContext
parameter that is passed into the filter
method. The getHeaders()
methodreturns the MultivaluedMap
on which you can put
your header(s).
您可以通过ClientRequestContext
传递给filter
方法的参数来操作标头。该getHeaders()
方法返回MultivaluedMap
您可以使用put
的标题。
You can registeryour custom ClientRequestFilter
with your ClientConfig
before you call newClient
.
您可以注册自定义ClientRequestFilter
你ClientConfig
打电话之前newClient
。
config.register(MyAuthTokenClientRequestFilter.class);
回答by Madura Pradeep
If you want to add only few headers in Jersey 2.x client, you can simply add it when request is sending as follows.
如果您只想在 Jersey 2.x 客户端中添加几个标头,您可以在请求发送时简单地添加它,如下所示。
webTarget.request().header("authorization":"bearer jgdsady6323u326432").post(..)...
回答by mojo-jojo
To add to what Pradeep said, there's also headers(MultivaluedMap < String, Objects> under WebTarget.request() if you have a gaggle of headers:
为了补充 Pradeep 所说的内容,如果您有一堆标题,那么 WebTarget.request() 下还有 headers(MultivaluedMap < String, Objects> :
MultivaluedMap head = new MultivaluedHashMap();
head.add("something-custom", new Integer(10));
head.add("Content-Type", "application/json;charset=UTF-8");
builder.headers ( head ); // builder from Joshua's original example