0

我使用 JERSEY 编写了 REST 网络服务。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;
    }
}

XSD:

<?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>

我已经使用 .xsd 从上面的 xsd 生成了 POJO Maven JAXB plugin。现在我有SumRequestSumResponsePOJO。

现在我怎么能写一个Jersey client通过传递下面的输入来获得响应?

<?xml version="1.0" encoding="ISO-8859-1"?>
<SumRequest xmlns="http://www.madbit.org/SumService">
 <element>1</element>
 <element>4</element>
</SumRequest>

谢谢!

4

1 回答 1

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

于 2013-09-20T11:20:15.910 回答