我使用JERSEY编写了RESt Web服务。 PFB我的终点。
package org.madbit.rest;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.madbit.rest.ws.SumRequest;
import org.madbit.rest.ws.SumResponse;
@Path("/services")
public class SumEndpoint {
@POST
@Path("sum")
@Produces(MediaType.APPLICATION_XML)
@Consumes(MediaType.APPLICATION_XML)
public SumResponse getSum(SumRequest request) {
SumResponse response = new SumResponse();
List<Integer> elements = request.getElement();
int sum = 0;
for (Integer element: elements)
sum += element;
response.setSum(sum);
return response;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.madbit.org/SumService" xmlns:tns="http://www.madbit.org/SumService" elementFormDefault="qualified">
<xs:element name="SumRequest">
<xs:complexType>
<xs:sequence>
<xs:element name="element" type="xs:int" minOccurs="1" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="SumResponse">
<xs:complexType>
<xs:sequence>
<xs:element name="sum" type="xs:int" minOccurs="1" maxOccurs="1"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
我使用Maven JAXB plugin
从xsd以上生成了POJO。现在我有SumRequest
和SumResponse
POJO。
现在我如何通过传递以下输入来编写Jersey client
以获得响应?
<?xml version="1.0" encoding="ISO-8859-1"?>
<SumRequest xmlns="http://www.madbit.org/SumService">
<element>1</element>
<element>4</element>
</SumRequest>
谢谢!
答案 0 :(得分:0)
这应该适合你:
public static void testWS(){
try{
SumRequest sumRequest = new SumRequest(1,4); //here you have to create your input object
Client client = Client.create();
WebResource service = client.resource("http://www.madbit.org/SumService");
/*
* here you are calling the post method with your input object attached
*/
ClientResponse response = service.type(MediaType.APPLICATION_XML).post(ClientResponse.class, sumRequest);
SumResponse res = response.getEntity(SumResponse.class);
System.out.println("output JaxbWS:\n " + res.toString());
}
catch(Exception e){
System.out.println(e.getMessage());
}
我必须补充一点,您传递的对象 SumRequest 将自动转换为XML,因为您的方法指定使用 XML。