3

更新

我几乎已经能够完成我的 RESTful 通信,但我还有一些问题:

1 - 如何将我的 XML 分配给连接(下面的代码将举例说明我的情况)?

调用 Web 服务

public Person getByAccount(Account account) {   
    URL url = new URL(uri);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Accept", "application/xml");

    XStream xstream = new XStream();
    String xmlIn = xstream.toXML(account);

    // Put the xmlIn into the connection

    BufferedReader br = new BufferedReader(new InputStreamReader(
        (connection.getInputStream())));

    StringBuilder sb = new StringBuilder();
    String line;
    while((line = br.readLine()) != null)
        sb.append(line);
    String xmlOut = sb.toString();

    connection.disconnect();
    return (Person) xstream.fromXML(xmlOut);
}

2 - 考虑到最后一个代码示例(Web 服务),下面的类会产生有效的 XML 输出吗?

使用 RESTful 发送的类

@XmlRootElement(name="people")
public class People {
    @XmlElement(name="person")
    public List<Person> people;

    public People() {
        people.add(new Person(1, "Jan"));
        people.add(new Person(2, "Hans"));
        people.add(new Person(3, "Sjaak"));
    }

    public List<Person> all() {
        return people;
    }

    public Person byName(String name) {
        for(Person person : people)
            if(person.name.equals(name))
                return person;

        return null;
    }

    public void add(Person person) {
        people.add(person);
    }

    public Person update(Person person) {
        for(int i = 0; i < people.size(); i++)
            if(person.id == people.get(i).id) {
                people.set(i, person);
                return person;
            }

        return null;
    }

    public void remove(Person person) {
        people.remove(person);
    }
}

网络服务

@GET
@Path("/byAccount")
@Consumes("application/xml")
@Produces("application/xml")
public Person getByAccount(Account account) {
    // business logic
    return person;
}
4

3 回答 3

4

尝试这个:

conn.setDoOutput(true);
OutputStream output = conn.getOutputStream();
// And write your xml to output stream.

检查此链接以使用标准的 REST URLhttp ://rest.elkstein.org/2008/02/using-rest-in-java.html

编辑

首先,您需要将您的getByAccount请求更改为POST请求,因为GET请求不允许在正文中传递任何信息,它仅使用 url 中的请求参数。但是您发送 XML,所以使用POST.

尝试以下版本的发送方法:

public Person getByAccount(Account account) {   
    URL url = new URL(uri);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Accept", "application/xml");
    connection.setOutput(true);

    XStream xstream = new XStream();
    xstream.toXML(account, connection.getOutputStream());

    Person person = (Person) xstream.fromXML(connection.getInputStream());   
    connection.disconnect();
    return person;
}
于 2012-06-03T09:46:03.890 回答
1

您可以使用Jersey Client API,(另外一个链接)进行最充分的调用。

于 2012-06-03T09:48:54.647 回答