簡體   English   中英

Java客戶端拋出不支持的媒體類型異常

[英]Java client throwing Unsupported Media Type Exception

我正在開發一個使用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; 

您沒有傳遞內容類型標頭; 我強烈建議使用像Apache Common HttpClient這樣的API來生成這樣的請求(也許可以從文件中讀取內容)。

@Riccardo是正確的,服務器上的Restlet資源正在檢查客戶端請求的Content-Type標頭,以確保您正在POST到服務器的實體具有它可以支持的類型。 這是一個Restlet 1.1示例 您會注意到該資源已設置為期望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)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM