我已经看过了如何使用 Jersey Client API 在 RESTful 调用上添加标头 https://stackoverflow.com/questions/18342456/how-to-add-headers-on-restful-call-using-jersey-client-api,但这适用于 Jersey 1.x。
如何在 Jersey 2.21 中设置标头值(例如授权令牌)?
这是我正在使用的代码:
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);
}
在 Jersey 2.0+ 中,您可以注册一个自定义实现ClientRequestFilter https://docs.oracle.com/javaee/7/api/javax/ws/rs/client/ClientRequestFilter.html这样可以操纵标题 https://jersey.github.io/documentation/latest/filters-and-interceptors.html#d0e9470在客户端 API 将发出的请求中。
您可以通过以下方式操作标题ClientRequestContext
传入的参数filter
方法。这getHeaders() method https://docs.oracle.com/javaee/7/api/javax/ws/rs/client/ClientRequestContext.html#getHeaders--返回MultivaluedMap
您可以在其中put
你的标题。
You can register https://jersey.github.io/documentation/latest/client.html#d0e4388你的定制ClientRequestFilter
和你的ClientConfig
在你打电话之前newClient
.
config.register(MyAuthTokenClientRequestFilter.class);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)