2
我寫了一個簡單的應用程序,使用Apache CXF
創建了一個服務器和一個客戶端。我希望當客戶端請求某個消息時,服務器將返回此消息。其他Web服務獲取對象作爲響應
我的代碼
public class Message {
private long id;
private String message;
private String author;
public Message() { }
public Message(long id, String message, String author) {
this.id = id;
this.message = message;
this.author = author;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
@Path("/messages")
public class MessageResource {
private MessageService messageService = new MessageService();
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<Message> getMessages() {
return messageService.getAllMessages();
}
@GET
@Path("/{messageId}")
@Produces(MediaType.APPLICATION_JSON)
public Message getMessage(@PathParam("messageId") int messageId) {
return messageService.getMessage(messageId);
}
}
public class MessageService {
private Map<Integer, Message> messages = new HashMap<>();
public MessageService() {
messages.put(1, new Message(1, "msg1", "author1"));
messages.put(2, new Message(2, "msg2", "author2"));
messages.put(3, new Message(3, "msg3", "author3"));
messages.put(4, new Message(4, "msg4", "author4"));
messages.put(5, new Message(5, "msg5", "author5"));
}
public List<Message> getAllMessages() {
return new ArrayList<Message>(messages.values());
}
public Message getMessage(int id) {
return messages.get(id);
}
}
public class Client
{
public static void main(String[] args)
{
JAXRSClientFactoryBean client = new JAXRSClientFactoryBean();
client.setResourceClass(Message.class);
client.setAddress("http://localhost:8080/messenger/messages/4");
WebClient wc = client.createWebClient();
Message msg = wc.get(Message.class);
System.out.println(msg);
}
}
public class Server {
public static void main(String[] args) {
JAXRSServerFactoryBean serverFactory = new JAXRSServerFactoryBean();
serverFactory.setResourceClasses(MessageResource.class);
serverFactory.setResourceProvider(MessageResource.class,
new SingletonResourceProvider(new MessageResource()));
serverFactory.setAddress("http://localhost:8080/messenger/");
serverFactory.setProvider(JacksonJsonProvider.class);
serverFactory.create();
}
}
我得到這個錯誤:No message body reader has been found for class app.Message, ContentType: application/json
。
誰能告訴我我做錯了什麼?我想獲得一個Message
對象作爲迴應。
根據[此線索](http://stackoverflow.com/questions/24653329/jaxrs-client-cont-find-message-body-writer/25536584#25536584),你需要在一個JSON提供您的運行。你是否有一個? – beosign