简体   繁体   English

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

[英]Java client throwing Unsupported Media Type Exception

I am developing an application that uses restful api. 我正在开发一个使用restful api的应用程序。 A java client sending a request to a standalone server is throwing Unsupported Media Type exception. 向独立服务器发送请求的Java客户端抛出了Unsupported Media Type异常。 The client code is as follows 客户端代码如下

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);

Server code is as follows 服务器代码如下

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; 

You are not passing the content-type header; 您没有传递内容类型标头; I strongly recommend using an API like Apache Common HttpClient to produce such requests (and maybe read the contents from a file). 我强烈建议使用像Apache Common HttpClient这样的API来生成这样的请求(也许可以从文件中读取内容)。

@Riccardo is correct, the Restlet Resource on the server is checking the Content-Type header of the client's request to make sure the entity you're POSTing to the server has a type it can support. @Riccardo是正确的,服务器上的Restlet资源正在检查客户端请求的Content-Type标头,以确保您正在POST到服务器的实体具有它可以支持的类型。 Here's a Restlet 1.1 example . 这是一个Restlet 1.1示例 You'll notice that that Resource is set up to expect XML: 您会注意到该资源已设置为期望XML:

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

So maybe your server side doesn't declare the representations it can handle, or it does and Restlet's automatic media type negotiation is detecting that your request doesn't have Content-Type: text/xml (or application/xml) set. 所以也许你的服务器端没有声明它可以处理的表示,或者它确实和Restlet的自动媒体类型协商检测到你的请求没有设置Content-Type:text / xml(或application / xml)。

So as @Riccardo suggests, use Apache HttpClient and call HttpRequest.setHeader("Content-Type", "text/xml"), or use Restlet's client library API to do this (it adds another abstraction layer on top of an HTTP client connector like Apache HttpClient). 所以@Riccardo建议使用Apache HttpClient并调用HttpRequest.setHeader(“Content-Type”,“text / xml”),或者使用Restlet的客户端库API来执行此操作(它在HTTP客户端连接器之上添加另一个抽象层)像Apache HttpClient)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM