[英]How to send headers and body using Jersey POST request?
我一直无法成功命中 API。 我需要在 POST 请求的正文中传递三个值和一个标头: "Content-Type":"application/x-www-form-urlencoded"
。
我得到了一个 400 状态,还有这个: Content-Type=[application/json;charset=UTF-8]
,有人能在这里指出我正确的方向吗?
Client client = ClientBuilder.newClient();
WebTarget webTarget = client.target(REST_URI).path("dummy/dummy"); // REST_URI is a constant containing the URL
// Create body content
String json = Json.createObjectBuilder()
.add("grant_type", "password")
.add("username", USERNAME) // USERNAME/PASSWORD are constants
.add("password", PASSWORD)
.build()
.toString();
Response response = webTarget.request(MediaType.APPLICATION_FORM_URLENCODED)
//.header("Content-Type", "application/x-www-form-urlencoded")
.accept(MediaType.APPLICATION_FORM_URLENCODED)
.post(Entity.entity(json, MediaType.APPLICATION_JSON));
您可以尝试使用以下代码。 您必须使用 .type() 方法,您必须在其中提及内容类型。
Response response = webTarget.resource(URL)
.accept(MediaType.APPLICATION_JSON)
.type(MediaType.APPLICATION_JSON)
.post(Entity.entity(json, MediaType.APPLICATION_JSON));
您也可以从以下链接中参考如何制作客户端。
https://howtodoinjava.com/jersey/jersey-restful-client-examples/#post
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.