2014-11-22 56 views
1

我試過official samples Wild JAX-RS的問題。並試圖使用:關於生產

curl http://localhost:8080/wildfly-helloworld-rs/rest/ -H 'accept:application/xml' 
curl http://localhost:8080/wildfly-helloworld-rs/rest/ -H 'accept:application/json' 

兩個要求返回我的XML表示:

<xml><result>Hello World!</result></xml> 

我甚至想補充一點:

@GET 
@Path("/") 
@Produces(MediaType.TEXT_PLAIN) 
@Consumes(MediaType.TEXT_PLAIN) 
public String getHelloWorldText() { 
    return helloService.createHelloMessage("World"); 
} 

它反正總是返回XML表示。

編輯:從聯例如

@Path("/") 
public class HelloWorld { 
    @Inject 
    HelloService helloService; 

    @GET 
    @Path("/") 
    @Produces({ "application/json" }) 
    public JsonObject getHelloWorldJSON() { 
     return Json.createObjectBuilder() 
       .add("result", helloService.createHelloMessage("World")) 
       .build(); 
    } 

    @GET 
    @Path("/") 
    @Produces({ "application/xml" }) 
    public String getHelloWorldXML() { 
     return "<xml><result>" + helloService.createHelloMessage("World") 
           + "</result></xml>"; 
    } 
} 

public class HelloService { 
    String createHelloMessage(String name) { 
     return "Hello " + name + "!"; 
    } 
} 

回答

3

它與其說是一個與JAX-RS的問題,因爲它與捲曲。如果我運行與-v開關(詳細)命令,我會看到請求頭

C:\temp\jboss\quickstart\helloworld-rs>curl 
         -v http://localhost:8080/wildfly-helloworld-rs/rest/ 
         -H 'accept:application/xml' 
* Adding handle: conn: 0x4b6208 
* Adding handle: send: 0 
* Adding handle: recv: 0 
* Curl_addHandleToPipeline: length: 1 
* - Conn 0 (0x4b6208) send_pipe: 1, recv_pipe: 0 
* About to connect() to localhost port 8080 (#0) 
* Trying 127.0.0.1... 
* Connected to localhost (127.0.0.1) port 8080 (#0) 
> GET /wildfly-helloworld-rs/rest/ HTTP/1.1 
> User-Agent: curl/7.30.0 
> Host: localhost:8080 
> Accept: */* 
> 'accept:application/xml' 
> 
< HTTP/1.1 200 OK 
< Connection: keep-alive 
< X-Powered-By: Undertow/1 
* Server WildFly/8 is not blacklisted 
< Server: WildFly/8 
< Content-Type: application/json 
< Content-Length: 25 
< Date: Sun, 23 Nov 2014 03:00:56 GMT 
< 
{"result":"Hello World!"}* Connection #0 to host localhost left intact 

C:\temp\jboss\quickstart\helloworld-rs> 

你可以看到,我得到JSON,當我用accept:application/xml

看看在Accept頭。這是*/*(你可以看到下面的accept:application/xml不被使用。話雖這麼說,當請求是模糊的,在配套配件我們的資源的方法而言,結果是不可預知的。對我來說,我總是得到JSON。

我不是一個很大的cURL用戶,所以我不知道-H交換機應該如何工作,並且它不在工作,但對於我來說'單引號不起作用,並且accept不會自動大寫(應該是Accept)。

所以使用-H "Accept:application/json",它應該工作。使用-v開關看到頭。

+1

這很有趣,只在Windows上引起這個問題。在Ubuntu上,我可以用'in -H寫入請求,並且它可以工作。無論如何,TNX,沒有它的工作) – Suvitruf 2014-11-23 10:21:20

+0

我的意思是「現在」(: – Suvitruf 2014-11-23 10:27:41

+0

我在Windows上。很高興知道:-) – 2014-11-23 10:42:47