草庐IT

java - 将 JSON 传递给 WebService

coder 2024-03-21 原文

我使用 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/

有关java - 将 JSON 传递给 WebService的更多相关文章

  1. ruby-on-rails - Rails HTML 请求渲染 JSON - 2

    在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这

  2. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  3. ruby - rails 3 redirect_to 将参数传递给命名路由 - 2

    我没有找到太多关于如何执行此操作的信息,尽管有很多关于如何使用像这样的redirect_to将参数传递给重定向的建议:action=>'something',:controller=>'something'在我的应用程序中,我在路由文件中有以下内容match'profile'=>'User#show'我的表演Action是这样的defshow@user=User.find(params[:user])@title=@user.first_nameend重定向发生在同一个用户Controller中,就像这样defregister@title="Registration"@user=Use

  4. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  5. ruby-on-rails - 如何生成传递一些自定义参数的 `link_to` URL? - 2

    我正在使用RubyonRails3.0.9,我想生成一个传递一些自定义参数的link_toURL。也就是说,有一个articles_path(www.my_web_site_name.com/articles)我想生成如下内容:link_to'Samplelinktitle',...#HereIshouldimplementthecode#=>'http://www.my_web_site_name.com/articles?param1=value1¶m2=value2&...我如何编写link_to语句“alàRubyonRailsWay”以实现该目的?如果我想通过传递一些

  6. ruby-on-rails - 如何使用 Rack 接收 JSON 对象 - 2

    我有一个非常简单的RubyRack服务器,例如:app=Proc.newdo|env|req=Rack::Request.new(env).paramspreq.inspect[200,{'Content-Type'=>'text/plain'},['Somebody']]endRack::Handler::Thin.run(app,:Port=>4001,:threaded=>true)每当我使用JSON对象向服务器发送POSTHTTP请求时:{"session":{"accountId":String,"callId":String,"from":Object,"headers":

  7. java - 我的模型类或其他类中应该有逻辑吗 - 2

    我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我

  8. java - 什么相当于 ruby​​ 的 rack 或 python 的 Java wsgi? - 2

    什么是ruby​​的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht

  9. ruby - 在 Ruby 中按名称传递函数 - 2

    如何在Ruby中按名称传递函数?(我使用Ruby才几个小时,所以我还在想办法。)nums=[1,2,3,4]#Thisworks,butismoreverbosethanI'dlikenums.eachdo|i|putsiend#InJS,Icouldjustdosomethinglike:#nums.forEach(console.log)#InF#,itwouldbesomethinglike:#List.iternums(printf"%A")#InRuby,IwishIcoulddosomethinglike:nums.eachputs在Ruby中能不能做到类似的简洁?我可以只

  10. Observability:从零开始创建 Java 微服务并监控它 (二) - 2

    这篇文章是继上一篇文章“Observability:从零开始创建Java微服务并监控它(一)”的续篇。在上一篇文章中,我们讲述了如何创建一个Javaweb应用,并使用Filebeat来收集应用所生成的日志。在今天的文章中,我来详述如何收集应用的指标,使用APM来监控应用并监督web服务的在线情况。源码可以在地址 https://github.com/liu-xiao-guo/java_observability 进行下载。摄入指标指标被视为可以随时更改的时间点值。当前请求的数量可以改变任何毫秒。你可能有1000个请求的峰值,然后一切都回到一个请求。这也意味着这些指标可能不准确,你还想提取最小/

随机推荐