Myc*_*haL 4 java spring web-services
我们想创建一个"WebService",它返回特定对象的列表.我们想通过apache http客户端库从另一个java程序中调用这个web服务.
此时,如果我们从Firefox调用Web服务,则会出现406错误页面.
我们是否必须使用JSON或XML来传输列表?怎么做,以及如何使用apache http客户端获取列表?
谢谢.
[编辑]
唯一有效的方法是使用JAXB注释创建一些实体,以便序列化为XML.
@XmlRootElement(name = "person")
public class Person {
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
@XmlRootElement(name = "persons")
public class PersonList {
@XmlElement(required = true)
public List<Person> persons;
public List<Person> getData() {
return persons;
}
public void setData(List<Person> persons) {
this.persons = persons;
}
}
@RequestMapping(value = "/hello.html", method = RequestMethod.GET, produces = "application/xml")
@ResponseBody
public ResponseEntity<PersonList> hello() {
PersonList test = new PersonList();
List<Person> rep = new ArrayList<Person>();
Person person1 = new Person();
person1.setId("1");
Person person2 = new Person();
person2.setId("2");
rep.add(person1);
rep.add(person2);
test.setData(rep);
// return test;
HttpHeaders responseHeaders = new HttpHeaders();
List<MediaType> medias = new ArrayList<MediaType>();
medias.add(MediaType.ALL);
responseHeaders.setAccept(medias);
return new ResponseEntity<PersonList>(test, responseHeaders, HttpStatus.OK);
}
Run Code Online (Sandbox Code Playgroud)
我尝试使用产品并直接返回对象,但仍然是错误406.XML + ResponseEntity工作.
这很奇怪,因为我看到一个非常简单的例子,将对象转换为json并出现在Web浏览器中.
那么,现在我必须了解如何获得响应并将XML转换为实体......
小智 11
该@ResponseBody注解告诉春天,我们将在响应正文被返回的数据,而不是渲染JSP.
使用@ResponseBody注释时,Spring将以客户端可接受的格式返回数据.也就是说,如果客户端请求有一个标头来接受json并且类路径中存在Jackson-Mapper,那么Spring将尝试将返回值序列化为JSON.如果请求标头指示XML为acceptable(accept=application/xml)且Jaxb在类路径中,并且返回类型使用Jaxb批注进行批注,则Spring将尝试将返回值编组为XML.
在2天内,我尝试了很多方法: - responseEntity - httpheaders - XML等...
对于JSON(默认行为),项目需要一个包含所有Spring库的库.这里是在Maven项目中声明的库.
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.7.1</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
没有这个库,我有一个错误(406).
无论如何,谢谢您的所有答案和建议.
| 归档时间: |
|
| 查看次数: |
50010 次 |
| 最近记录: |