我正在开发一个需要通过CXF Web服务连接到远程数据库的Android应用程序。我尝试过使用Soap,但是由于各种问题留下了选项,并采用了基于REST的轻量级服务(通过添加对现有cxf Web服务的注释。)我有一个从活动内部调用的Rest客户端。 我使用简单的参数,如String,int等。现在我想传递一个用户定义的对象 到服务并从服务器端获取一些String值。我该怎么做? 请帮助...在谷歌搜索我发现有关使用JSON,JAXB等的文章,但我不知道这些做什么或如何使用这些。我对使用这些技术编程非常陌生。
答案 0 :(得分:2)
您可以为客户端代码执行类似的操作:
private static final String URI = "http://localhost/rest/customer";
private Customer readCustomer(String id) {
try {
URL url = new URL(URI + "/" + id);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/xml");
InputStream data = connection.getInputStream();
// TODO - Read data from InputStream
connection.disconnect();
return customer;
} catch(Exception e) {
throw new RuntimeException(e);
}
}
private void createCustomer(Customer customer) {
try {
URL url = new URL(URI);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/xml");
OutputStream os = connection.getOutputStream();
// TODO - Write data to OutputStream
os.flush();
connection.getResponseCode();
connection.disconnect();
} catch(Exception e) {
throw new RuntimeException(e);
}
}
private void updateCustomer(Customer customer) {
try {
URL url = new URL(URI);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("PUT");
connection.setRequestProperty("Content-Type", "application/xml");
OutputStream os = connection.getOutputStream();
// TODO - Write data to OutputStream
os.flush();
connection.getResponseCode();
connection.disconnect();
} catch(Exception e) {
throw new RuntimeException(e);
}
}
private void deleteCustomer(String id) {
try {
URL url = new URL(URI + "/" + id);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("DELETE");
connection.getResponseCode();
connection.disconnect();
} catch(Exception e) {
throw new RuntimeException(e);
}
}