错误:不支持的媒体类型(代号1)

时间:2016-01-20 23:59:41

标签: java codenameone netbeans-8

我尝试从NetBeans IDE上的CN1应用程序发送POST请求,但每次运行应用程序时都会出现此错误"错误415:不支持的媒体类型"。这是我的代码:

请求代码:

@Override
    protected void onMain_ButtonAction(Component c, ActionEvent event) {
    String name=findTextField(c).getText();
    String qty=findTextField1(c).getText();

    ConnectionRequest r= new ConnectionRequest(){                       
           @Override
            protected void readResponse(InputStream input) throws IOException {                              
                 }                  
           };    
       r.setUrl("http://localhost:8080/webservicess/webresources/getreq/post");
       r.setPost(true);
       r.setHttpMethod("POST");       
       r.addArgument("name", name);
       r.addArgument("quantity", qty);
       NetworkManager.getInstance().addToQueueAndWait(r);          
    }

}

REST服务

@POST
    @Path("post")
    @Consumes("application/json")
    public void putJson(Product product) {

        String result = "Product recieved : " + product;
        System.out.println(""+result);
    }
}

Product.java类

class Product {
    public String name;
    public int quantity;

    Product(){

    }

}

请查看附图,了解错误消息的屏幕截图。 我想要一种情况,当我点击提交按钮时,输入的产品名称和数量值应该显示在REST控制台上。请来救我吧。

simulator screenshot

最诚挚的问候,

Yahya-Imam Munir Kolapo

1 个答案:

答案 0 :(得分:1)

基于POST JSON fails with 415 Unsupported media type, Spring 3 mvc

您需要设置接受请求标头,您可以在Codename OneaddRequestHeader中设置:

r.addRequestHeader("accept", "application/json");

你遇到的另一个问题是有点误导,但我猜测web服务接受正文中的JSON而不是标准的post参数,所以这应该可行:

final String name = findTextField(c).getText();
final String qty = findTextField1(c).getText();

ConnectionRequest r= new ConnectionRequest(){    
        @Override
        protected void buildRequestBody(OutputStream os) throws IOException {
            StringBuilder val = new StringBuilder("{\"name\":\"");
            val.append(name);
            val.append("\",\"quantity\":");
            val.append(qty);
            val.append("}");
            if(shouldWriteUTFAsGetBytes()) {
                os.write(val.toString().getBytes("UTF-8"));
            } else {
                OutputStreamWriter w = new OutputStreamWriter(os, "UTF-8");
                w.write(val.toString());
            }                                  
        }
        @Override
        protected void readResponse(InputStream input) throws IOException {                              
        }                  
       };    
   r.setUrl("http://localhost:8080/webservicess/webresources/getreq/post");
   r.setPost(true);
   NetworkManager.getInstance().addToQueueAndWait(r);