是的,这是一个小例子:
@Path("/recipe")
public class RecipeResource {
@GET
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public List<Recipe> getRecipesBrowser() {
System.out.println("REST Service Method getRecipesBrowser called");
System.out.println("Called URI: " + uriInfo.getAbsolutePath());
List<Recipe> dummyData = new ArrayList<>();
dummyData.add(new Recipe(new Long(1), "Recipe1", "Description1", null));
dummyData.add(new Recipe(new Long(2), "Recipe2", "Description2", null));
dummyData.add(new Recipe(new Long(3), "Recipe3", "Description3", null));
dummyData.add(new Recipe(new Long(4), "Recipe4", "Description4", null));
dummyData.add(new Recipe(new Long(5), "Recipe5", "Description5", null));
dummyData.add(new Recipe(new Long(6), "Recipe6", "Description6", null));
dummyData.add(new Recipe(new Long(7), "Recipe7", "Description7", null));
dummyData.add(new Recipe(new Long(8), "Recipe8", "Description8", null));
dummyData.add(new Recipe(new Long(9), "Recipe9", "Description9", null));
return dummyData;
}
}
Recipe 的 POJO 需要注解 @XMlRootElement:
@XmlRootElement
public class Recipe {
private Long recipeId;
private String name;
private String description;
private List<Fixing> fixings;
public Recipe() {
}
public Recipe(Long id, String name, String description, List<Fixing> fixings) {
super();
this.recipeId = id;
this.name = name;
this.description = description;
this.fixings = fixings;
}
public Long getRecipeId() {
return recipeId;
}
public void setRecipeId(Long id) {
this.recipeId = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<Fixing> getFixings() {
return fixings;
}
public void setFixings(List<Fixing> fixings) {
this.fixings = fixings;
}
}
然后您将进入您的浏览器 XML 并在使用 REST 客户端 JSON 时:
在 Chrome 中请求 URL
http://test:8080/YourService/rest/recipe
Chrome 请求标头是:
GET /YourService/rest/recipe HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)
在高级 REST 客户端中,请求标头是:
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/33.0.1750.117 Safari/537.36
Content-Type: text/plain; charset=utf-8
Accept: */*
Accept-Encoding: gzip,deflate,sdch
Accept-Language: de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4
Cookie: beaker.session.id=f1f5577e0dd2047968a2ada05acc1952; nas_lang=ENG
区别在于Request Header Accept。浏览器将其设置为
接受:text/html,application/xhtml+xml,application/xml
REST 客户端将其设置为
接受:/
因此,使用此参数,您可以影响 xou 是否接收 JSON 或 XML 作为响应。