java – 将JSON传递给WebService
发布时间:2020-12-15 03:12:23 所属栏目:Java 来源:网络整理
导读:我使用dropwizard框架在 java中开发了一个web服务.我希望它消耗一个json. 我的服务代码是 – – 资源等级 @Path(value = "/product") public class ProductResource{ @POST @Path(value = "/getProduct") @Consumes(MediaType.APPLICATION_JSON) @Produces(M
我使用dropwizard框架在
java中开发了一个web服务.我希望它消耗一个json.
我的服务代码是 – – 资源等级 @Path(value = "/product") public class ProductResource{ @POST @Path(value = "/getProduct") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Product getProduct(InputBean bean) { // Just trying to print the parameters. System.out.println(bean.getProductId()); return new Product(1,"Product1-UpdatedValue",1,1); } } – InputBean是一个简单的bean类. public class InputBean { private int productId; private String productName; public String getProductName() { return productName; } public void setProductName(String productName) { this.productName= productName; } public int getProductId() { return productId; } public void setProductId(int productId) { this.productId= productId; } } 客户代码 – public String getProduct() { Client client = Client.create(); WebResource webResource = client.resource("http://localhost:8080/product/getProduct"); JSONObject data = new JSONObject ("{"productId": 1,"productName": "Product1"}"); ClientResponse response = webResource.type(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .post(ClientResponse.class,data); return response.getEntity(String.class); } 我收到一个错误 – ClientHandlerException 这段代码有什么问题吗? JSONObject data = new JSONObject ("{"productId": 1,"productName": "Product1"}"); ClientResponse response = webResource.type(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .post(ClientResponse.class,data); 有人可以指出我可能会缺少什么吗? 客户日志 – 解决方法
您正确设置类型并正确地发出请求.
问题是你无法处理响应. A message body reader for Java class my.class.path.InputBean …基本上是在说,你要归还的东西是无法读取,格式化和输入任何有用的东西. 您在服务中返回了一个Product类型,这是您的八位字节流,但是我没有看到您将MessageBodyWriter输出到JSON的位置. 你需要: @Provider @Produces( { MediaType.APPLICATION_JSON } ) public static class ProductWriter implements MessageBodyWriter<Product> { @Override public long getSize(Product data,Class<?> type,Type genericType,Annotation annotations[],MediaType mediaType) { // cannot predetermine this so return -1 return -1; } @Override public boolean isWriteable(Class<?> type,Annotation[] annotations,MediaType mediaType) { if ( mediaType.equals(MediaType.APPLICATION_JSON_TYPE) ) { return Product.class.isAssignableFrom(type); } return false; } @Override public void writeTo(Product data,MediaType mediaType,MultivaluedMap<String,Object> headers,OutputStream out) throws IOException,WebApplicationException { if ( mediaType.equals(MediaType.APPLICATION_JSON_TYPE) ) { outputToJSON( data,out ); } } private void outputToJSON(Product data,OutputStream out) throws IOException { try (Writer w = new OutputStreamWriter(out,"UTF-8")) { gson.toJson( data,w ); } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |