gpt4 book ai didi

java - RESTful WebService 消费XML,如何调用?

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:53:31 26 4
gpt4 key购买 nike

更新

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

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

调用网络服务

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;
}

最佳答案

试试这个:

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

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

编辑

首先,您需要将getByAccount 请求更改为POST 请求,因为GET 请求不允许传递任何信息在 body 中,它仅使用 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;
}

关于java - RESTful WebService 消费XML,如何调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10869263/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com