2012-12-17 37 views
6

我正在嘗試使用Service/Dispatch機制來發布JAX-RS資源。問題是傳出請求的內容類型被鎖定爲text/xml。我看不出有什麼方法可以改變這種類型,例如application/xmlJAX-WS發送請求設置Content-Type

RESTfull web服務僅消耗application/xmlapplication/json。這是我使用的代碼:

public static void main(String[] args) { 
    QName qName = new QName("GREETINGS"); 

    Service service = Service.create(qName); 
    service.addPort(qName, HTTPBinding.HTTP_BINDING, "http://localhost:8081/gf-ws-1/resources/greetings"); 

    // change headers of the outgoing request 
    Map<String, Object> headers = new HashMap<String, Object>(); 
    headers.put("Content-Type", Arrays.asList(new String[] {"application/xml"})); 
    headers.put("Accept", Arrays.asList(new String[] {"zoo"})); 
    headers.put("foo", Arrays.asList(new String[] {"bar"})); 

    Dispatch<Source> dispatch = service.createDispatch(qName, Source.class, Service.Mode.PAYLOAD); 
    dispatch.getRequestContext().put(MessageContext.HTTP_REQUEST_METHOD, "POST"); 
    dispatch.getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS, headers); 

    dispatch.invokeOneWay(new StreamSource(new StringReader("<?xml version='1.0' encoding='UTF-8'?><greeting><value>Hello World!</value></greeting>"))); 

    // get the response code: [HTTP/1.1 415 Unsupported Media Type] because of content type 
    System.out.println(((Map<String, Object>) dispatch.getResponseContext().get(MessageContext.HTTP_RESPONSE_HEADERS)).get(null)); 
} 

Accept頭被修改爲zoofoo標頭被添加與值bar,但Content-Type保持不變。我想我可以使用一個過濾器並根據一些條件修改Content-Type,或者甚至基於foo頭,但這似乎違反直覺。

這裏是請求的所有標題:

POST /gf-ws-1/resources/greetings HTTP/1.1 
Accept: zoo 
Content-Type: text/xml 
foo: bar 
User-Agent: Metro/2.2.0-1 (tags/2.2.0u1-7139; 2012-06-02T10:55:19+0000) JAXWS-RI/2.2.6-2 JAXWS/2.2 svn-revision#unknown 
Host: localhost:8080 
Connection: keep-alive 
Content-Length: 86 

任何幫助表示讚賞。

回答

1

如果要定製整個消息,則必須使用Service.Mode.MESSAGE而不是Service.Mode.PAYLOAD。

Content-Type是與消息有關的屬性。