我有 REST 服务,可以使用未编码的域实体进行响应。例如:
Request:
GET http://someAddress.com/customer/001
Response:
<customer>
<id>001</id>
<name>Some Guy</name>
...
</customer>
我想添加一些链接到发现服务的响应。例如:
<customer>
<id>001</id>
<name>Some Guy</name>
...
<link xml:link="delete" href="http://someAddress.com/customer/001"/>
</customer>
我担心的是这是否会导致编码问题。我希望链接可发现,但我希望消费者可以轻松使用域模式,它不包含链接元素。
将链接放在回复中的其他地方是否更好?如果有,在哪里?
最佳答案
假设您将 JAXB 用于对象到 XML 层,您可以使用 XmlAdapter 执行类似以下操作,但您需要一个用于链接的对象而不是字符串:
import java.net.HttpURLConnection;
import java.net.URL;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class CustomerAdapter extends XmlAdapter<String, Customer>{
private JAXBContext jaxbContext;
public CustomerAdapter() {
try {
jaxbContext = JAXBContext.newInstance(Customer.class);
} catch(JAXBException e) {
throw new RuntimeException(e);
}
}
@Override
public String marshal(Customer v) throws Exception {
if(null == v) {
return null;
}
return "http://someAddress.com/customer/" + v.getId();
}
@Override
public Customer unmarshal(String v) throws Exception {
if(null == v) {
return null;
}
URL url = new URL(v);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/xml");
Customer customer = (Customer) jaxbContext.createUnmarshaller().unmarshal(connection.getInputStream());
connection.disconnect();
return product;
}
}
有关 XmlAdapter 的更多信息,请参阅:
关于java - 添加指向 REST 响应的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5235952/