使用@Produces我學習Jersey webservices
和跨越@Produces
用法來了,所以要了解它,我已經寫了一個小程序是這樣的:不同的方法
@Path("users/{username: [a-zA-Z][a-zA-Z_0-9]*}")
public class UserResource {
@GET
@Produces("text/plain")
public String getUser(@PathParam("username") String userName) {
return "Hello " + userName;
}
@GET
@Produces({"application/xml", "application/json"})
public String doGetAsXmlOrJson(@PathParam("username") String userName) {
return "<text>Hello World</text>";
}
}
當我將請求爲http://localhost:9998/users/Java
,沿標題爲「Accept:application/json」,那麼我期待輸出爲<text>Hello World</text>
。但相反,我得到它作爲Hello Java
。我正在使用Chrome瀏覽器的郵遞員客戶端來測試。
現在,如果我在上面的程序中刪除getUser
方法,那麼我得到的輸出爲<text>Hello World</text>
。
你能告訴我爲什麼即使當我設置接受標題,請求不會去我的doGetAsXmlOrJson
方法?
更新: -添加更多細節
該程序正在使用下面的代碼作爲Jersey documentation提到的部署:
import java.io.IOException;
import java.net.URI;
import javax.ws.rs.core.UriBuilder;
import org.glassfish.grizzly.http.server.HttpServer;
import com.sun.jersey.api.container.grizzly2.GrizzlyServerFactory;
import com.sun.jersey.api.core.PackagesResourceConfig;
import com.sun.jersey.api.core.ResourceConfig;
public class Main {
private static URI getBaseURI() {
return UriBuilder.fromUri("http://localhost/").port(9998).build();
}
public static final URI BASE_URI = getBaseURI();
protected static HttpServer startServer() throws IOException {
System.out.println("Starting grizzly...");
ResourceConfig rc = new PackagesResourceConfig("com.examples.Jersey1");
return GrizzlyServerFactory.createHttpServer(BASE_URI, rc);
}
public static void main(String[] args) throws IOException {
HttpServer httpServer = startServer();
System.out.println(String.format("Jersey app started with WADL available at "
+ "%sapplication.wadl\nTry out %shelloworld\nHit enter to stop it...",
BASE_URI, BASE_URI));
System.in.read();
httpServer.stop();
}
}
這是我如何使用郵差客戶端測試:
該問題無法用您提供的代碼重現。我使用的是同一版本(1.19 - 來自您的其他帖子),我已經測試過郵差和cURL。確保你正確設置了Accept頭。如果您確定您正確設置標題,那麼您不會向我們顯示真實的代碼。我的看法是,這兩件事中只有一件可能是問題所在。 –
@peeskillet,我已經更新了所有關於測試程序的信息,請檢查。 – user3181365
您在圖片 –