【问题标题】:Jersey Client - How to send List in a form with a POST requestJersey 客户端 - 如何通过 POST 请求以表单形式发送列表
【发布时间】:2015-07-08 20:17:03
【问题描述】:

我正在使用 jersey 客户端将 POST 请求发送到 Web 服务器。我通常使用键值对构建 Form 对象。但是,我现在必须在我的请求中发送一个 List。这是我的代码的精简版

// Phone is a POJO consisting of a few Strings
public void request(List<Phone> phones) {
     Form form = new Form();
     form.add("phones", phones);
     ClientResponse response = WebService.getResponseFromServer(form);
     String output = response.getEntity(String.class);
     System.out.println(output);
}

public static ClientResponse getResponseFromServer(Form form) {
    Client client = createClient();
    WebResource webResource = client.resource(PATH);

    return webResource.type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class, form);
}

不幸的是,这似乎不起作用,并且我收到 400 bad request 错误。当我直接发送请求时

{"phones":[{"areaCode":"217","countryCode":"01","number":"3812565"}]}

我没有问题。提前致谢!

【问题讨论】:

    标签: java json rest jakarta-ee jersey


    【解决方案1】:

    以您的示例为例,基于典型的 POJO 序列化,您需要的不是 List&lt;Phone&gt;,而是具有 List&lt;Phone&gt; 类型的成员 phones 的类,否则有效负载将如下所示:

    [{"areaCode":"217","countryCode":"01","number":"3812565"}]
    

    首先,您需要一个具有 JSON 序列化功能的球衣客户端。您需要在依赖项中包含 jersey-json(以及 jersey-client)。 Maven 中的示例:

    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-client</artifactId>
        <version>1.19</version>
    </dependency>
    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-json</artifactId>
        <version>1.19</version>
    </dependency>
    

    像这样创建你的客户端:

    ClientConfig clientConfig = new DefaultClientConfig();
    clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
    Client client = Client.create(clientConfig);
    

    假设你有一个变量phones,它是 POJO,你可以这样称呼:

    ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).post(ClientResponse.class, phones);
    

    【讨论】:

    • 我需要注释我的电话 pojo 吗?我收到:从客户端生成响应时出错:com.sun.jersey.api.client.ClientHandlerException:com.sun.jersey.api.client.ClientHandlerException:Java 类型、电话类和 MIME 媒体的消息正文编写器类型,应用程序/json,未找到
    • 不,你不需要。您是否正确设置了clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
    • 我做到了,是的。不知道可能是什么问题。
    • 您使用的是哪个版本的球衣?
    • 球衣 1.19。问题最终是缺少将 Pojo 映射到 json 的依赖项。将genson添加到项目后,它起作用了。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 2022-06-20
    • 1970-01-01
    • 1970-01-01
    • 2017-05-17
    • 1970-01-01
    • 2021-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多