我使用 dropwizard 框架在 java 中开发了一个网络服务。我想让它消耗一个 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, 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
...基本上是说,您正在返回一些无法读取、格式化和输出到任何有用的东西。
您在您的服务中返回一个产品类型,这是您的八位字节流,但我看不到您在哪里有 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, Type genericType, Annotation[] annotations, MediaType mediaType)
{
if ( mediaType.equals(MediaType.APPLICATION_JSON_TYPE) )
{
return Product.class.isAssignableFrom(type);
}
return false;
}
@Override
public void writeTo(Product data, Class<?> type, Type genericType, Annotation[] annotations, 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 );
}
}
}
关于java - 将 JSON 传递给 WebService,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23642171/