简体   繁体   中英

Java client throwing Unsupported Media Type Exception

I am developing an application that uses restful api. A java client sending a request to a standalone server is throwing Unsupported Media Type exception. 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).

@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. Here's a Restlet 1.1 example . You'll notice that that Resource is set up to expect 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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