如何使用Jersey POST请求发送标题和正文?

问题描述 投票:0回答:1

我无法成功访问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));
java rest post jersey content-type
1个回答
0
投票

您可以尝试以下代码。您必须使用方法.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

© www.soinside.com 2019 - 2024. All rights reserved.