Я начинаю с отдыха и не знаю, как правильно его реализовать. У меня есть упражнение: я должен реализовать Rest-Client с RestClient-API из стандартной библиотеки javax.ws.rs, и я попытался использовать код ниже, но я получаю исключение из null-указателя. Но ресурс есть и когда я пытаюсь напрямую из браузера (http://localhost:8080/sep/rest/customers/112). Теперь мой вопрос, как я могу сделать это правильно. Некоторые ограничения, я должен использовать XML (не JSON) для поддержки данных.Клиент для отдыха: Javax.ws.rs
Hier мой клиент-код:
public Response createCustomer(Customer customer){
log.info("Starting: Rest Create a Customer with Name: " + Customer.class.getName());
this.customerWebTarget = this.client.target(URL);
Response response = this.customerWebTarget.request().
buildPost(Entity.entity(customer, MediaType.APPLICATION_XML)).invoke();
log.info("Ending: Rest Create a Customer with Name: " + response.getEntity().getClass().getName());
return response;
}
CustomerResource-код: Код
@Path("customers")
public class CustomerResource implements IAllowedMethods<Customer> {
private static final long serialVersionUID = -6367055402693237329L;
private Logger logger = Logger.getLogger(CustomerResource.class.getName());
@Inject
private CustomerService service;
public CustomerResource() {
logger.info("create of instance " + this.getClass().getName());
}
@Override
@GET
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response get() {
List<Customer> list = service.loadAll(Customer.FINDALL, Customer.class);
if (list != null && !list.isEmpty()) {
ResponseCustomerList responseList = new ResponseCustomerList();
responseList.setList(list);
return Response.ok(responseList).build();
}
return Response.status(Status.NOT_FOUND).build();
}
.
.
.
Заказчик:
import de.ostfalia.sep.adapter.XMLIntegerAdapter;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Customer implements Serializable {
private static final long serialVersionUID = 80668466040239995L;
@XmlID
@XmlJavaTypeAdapter(XMLIntegerAdapter.class)
private Integer customerNumber;
private String customerName;
private String contactLastName;
private String contactFirstName;
private String phone;
private String addressLine1;
private String addressLine2;
private String city;
private String state;
private String postalCode;
private String country;
@XmlIDREF
private Employee salesRepEmployee;
private BigDecimal creditLimit;
private Set<Payment> payments;
private Set<Order> orders;
public Customer() {
}
public Customer(Integer customernumber) {
this.customerNumber = customernumber;
}
public Customer(Integer customerNumber, String customerName, String contactLastName, String contactFirstName,
String phone, String addressLine1, String city, String country) {
this.customerNumber = customerNumber;
this.customerName = customerName;
this.contactLastName = contactLastName;
this.contactFirstName = contactFirstName;
this.phone = phone;
this.addressLine1 = addressLine1;
this.city = city;
this.country = country;
}
public Integer getCustomerNumber() {
return customerNumber;
}
public void setCustomerNumber(Integer customerNumber) {
this.customerNumber = customerNumber;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getContactLastName() {
return contactLastName;
}
public void setContactLastName(String contactLastName) {
this.contactLastName = contactLastName;
}
public String getContactFirstName() {
return contactFirstName;
}
public void setContactFirstName(String contactFirstName) {
this.contactFirstName = contactFirstName;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddressLine1() {
return addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public String getAddressLine2() {
return addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public Employee getSalesRepEmployee() {
return salesRepEmployee;
}
public void setSalesRepEmployee(Employee salesRepEmployee) {
this.salesRepEmployee = salesRepEmployee;
}
public BigDecimal getCreditLimit() {
return creditLimit;
}
public void setCreditLimit(BigDecimal creditLimit) {
this.creditLimit = creditLimit;
}
@Override
public int hashCode() {
int hash = 0;
hash += (customerNumber != null ? customerNumber.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are
// not set
if (!(object instanceof Customer)) {
return false;
}
Customer other = (Customer) object;
if ((this.customerNumber == null && other.customerNumber != null)
|| (this.customerNumber != null && !this.customerNumber.equals(other.customerNumber))) {
return false;
}
return true;
}
@Override
public String toString() {
return customerNumber.toString();
}
public Set<Payment> getPayments() {
return payments;
}
public void setPayments(Set<Payment> payments) {
this.payments = payments;
}
public Set<Order> getOrders() {
return orders;
}
public void setOrders(Set<Order> orders) {
this.orders = orders;
}
}
Это получилось, это как-то связано с URL-адресом ... Когда я даю URL-адрес (http: // localhost: 8080/sep/rest/customers/112) в запросе, он работает, но когда я добавьте его как URL + «112», похоже, он не делает то же самое. – Lycone
Используйте 'target (URL) .path (" 112 ")', если вы хотите добавить '112' в цель' ../ customers' –
Я пытаюсь извлечь из ответа клиента, но у меня есть исключение, некоторые аннотации отсутствуют ... Вот код сервера. «Не удается найти MessageBodyReader приложения типа содержимого/xml и типа класса ... Клиент». Я передаю эту аннотацию на своем Сервере. – Lycone