Java客户端抛出不支持的媒体类型异常

时间:2011-03-15 14:14:49

标签: java restlet

我正在开发一个使用restful api的应用程序。向独立服务器发送请求的Java客户端抛出了Unsupported Media Type异常。 客户端代码如下

StringBuilder xml = new StringBuilder();
                xml.append("<?xml version=\"1.0\" encoding=\"${encoding}\"?>").append("\n");
                xml.append("<root>").append("\n");
                xml.append("<user>").append("\n");
                xml.append("<username>"+username+"</username>");
                xml.append("\n");
                xml.append("<password>"+pass+"</password");
                xml.append("\n");
                xml.append("</user>");
                xml.append("</root>");
                Representation representation = new StringRepresentation(xml.toString());
                new ClientResource("http://localhost:7777/Auth").post(representation);

服务器代码如下

new Server(Protocol.HTTP,7777,TestServer.class).start();
String username = (String) getRequest().getAttributes().get("username");
        String password=(String) getRequest().getAttributes().get("password");
        StringRepresentation representation = null; 

2 个答案:

答案 0 :(得分:2)

您没有传递内容类型标题;我强烈建议使用像Apache Common HttpClient这样的API来生成这样的请求(并且可以从文件中读取内容)。

答案 1 :(得分:0)

@Riccardo是正确的,服务器上的Restlet资源正在检查客户端请求的Content-Type标头,以确保您正在POST到服务器的实体具有它可以支持的类型。这是一个Restlet 1.1 example。您会注意到该资源已设置为期望XML:

// Declare the kind of representations supported by this resource.  
getVariants().add(new Variant(MediaType.TEXT_XML));  

所以也许你的服务器端没有声明它可以处理的表示,或者它确实和Restlet的自动媒体类型协商检测到你的请求没有Content-Type:text / xml(或application / xml)集

正如@Riccardo建议的那样,使用Apache HttpClient并调用HttpRequest.setHeader(“Content-Type”,“text / xml”),或者使用Restlet的客户端库API来执行此操作(它在其上添加了另一个抽象层) HTTP客户端连接器,如Apache HttpClient)。

相关问题