java - 客户端传递参数

标签 java web-services rest

我使用 RESTful Web 服务。在此 Web 服务中,我必须传递一个我想保存为参数的 bean。

这是服务器代码:

@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Unidade inserir(Unidade unidade){
    Session s = ConnectDb.getSession();
    try {
        s.getTransaction().begin();
        s.save(unidade);
        s.getTransaction().commit();
        return unidade;
    } catch (Exception e) {
        e.printStackTrace();
        s.getTransaction().rollback();
        return null;
    } finally {
        s.close(); 
    }
}

我在客户端中有以下代码:

ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource webResource = client.resource("http://localhost:8080/RestauranteWeb/rest/unidades/7");
Builder builder = webResource.accept(MediaType.APPLICATION_JSON); 
GenericType<Unidade> genericType = new GenericType<Unidade>() {};

Unidade u = new Unidade();
u.setUnidSigla("KG");
//How to pass this bean as parameter?

Unidade response = builder.post(genericType);
System.out.println(response);

如何将 bean 作为参数传递给方法?

最佳答案

使用 Jackson 作为序列化器/反序列化器

如果您的 Unidade 对象使用 Jackson 注释和/或注册了 Deserializer 那么您应该能够使用 POST >BODY 包含表示 Unidade 对象的 JSON。它应该被神奇地反序列化并重建为服务器端的对象。

重要

确保在 POST 请求中添加 Content-Type header ,其值为 application/json。如果没有这个 header ,您的 Jersey 可能不知道如何处理正文。

您将使用 Jackson ObjectMapper 将您的 Unidade 对象序列化为 JSON 并发送该对象而不是 GenericType 东西是。

我有 Jersey 和 RESTEasy 实现,它们以这种方式与 Jackson 无缝协作。

关于java - 客户端传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17775223/

相关文章:

asp.net - 如何在 IIS 中托管没有 SVC 文件的 WCF 服务

java - JAX-WS wsimport 不会保留 toString()?

javascript - 了解 $resource 工厂和 @ 前缀

java - Maven 程序集插件不排除存档中的资源

java - 使用 Spring Boot 和 Spring Security 的 OpenID (OAuth2) 授权失败

java - 我需要帮助将绘画组件添加到类中的框架

rest - 使用 POST 创建请求,响应代码 200 或 201 和内容

java - 有什么方法可以调整 Java 游戏上的组件大小吗?

iphone - 从 iOS 上的 .net Web 服务获取数据

java - 使用spring boot的json输出中的日期格式