【问题标题】:POST using JAX-RS 2.0 Client API使用 JAX-RS 2.0 客户端 API 发布
【发布时间】:2014-07-11 12:58:24
【问题描述】:

我有一个 REST 服务,它使用表单参数公开一个 POST 服务:

@POST
@Path("/add")
@Produces("text/html")
public Response create(@FormParam("key")String key,
            @FormParam("value")String value)
{    
    service.addToList(key,value);    
    return Response.ok(RESPONSE_OK).build();     

} 

我需要找到一种方法来使用 JAX-RS 客户端 API 调用此服务。不幸的是,网络上唯一可用的示例使用传递给您的 Web 目标资源的 Entity 类:

StoreOrder order = new StoreOrder(...);
WebTarget myResource = client.target("http://example.com/webapi/write");
TrackingNumber trackingNumber = myResource.request(MediaType.APPLICATION_XML)
                                   .post(Entity.xml(order), TrackingNumber.class);

知道如何调用传递单个参数(可能是表单参数)的服务吗? 谢谢!

【问题讨论】:

    标签: rest jakarta-ee java-ee-7


    【解决方案1】:

    您应该使用:javax.ws.rs.client.Entity<T>javax.ws.rs.core.Form 结合使用。这是一个简单的例子:

    Client client = ClientBuilder.newClient();
    WebTarget target = client.target("http://localhost:9998").path("resource");
    
    Form form = new Form();
    form.param("key", "foo");
    form.param("value", "bar");
    
    TrackingNumber requestResult =
    target.request(MediaType.APPLICATION_JSON_TYPE)
        .post(Entity.entity(form,MediaType.APPLICATION_FORM_URLENCODED_TYPE),
            TrackingNumber.class);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多