在我的应用程序中,我必须从服务器获取一些分配的列表。在服务器上,我有一个方法,比如 fetchAssignments(int ,String),它以两个值作为参数。
- 期间(今天、当月或当周)- 整数
- 用户 ID - 字符串
此函数以 XML 流的形式返回分配列表。我知道如何连接到 http 服务器。但我不知道如何在服务器上调用该方法并将这些参数传递给它。谁能建议我更好的方法......?
最佳答案
您可以使用 HTTP GET 请求从服务器请求 XML 作为 InputStream,并将参数作为请求参数传递:
http://some.server/webapp?period=1&userid=user1
使用类似于下面的方法,您可以从服务器获取流:
/**
* Returns an InputStream to read from the given HTTP url.
* @param url
* @return InputStream
* @throws IOException
*/
public InputStream get(final String url) throws IOException {
HttpClient httpClient = new DefaultHttpClient();
HttpParams httpParams = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT);
HttpGet httpget = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpget);
StatusLine statusLine = httpResponse.getStatusLine();
if(! statusLine.getReasonPhrase().equals("OK")) {
throw new IOException(String.format("Request failed with %s", statusLine));
}
HttpEntity entity = httpResponse.getEntity();
return entity.getContent();
}
然后您可以使用“简单”(http://simple.sourceforge.net/) XML 库将 XML 解析为类似 JAXB 的实体:
/**
* Reads the XML from the given InputStream using "Simple" and returns a list of assignments.
* @param InputStream
* @return List<Assignment>
*/
public List<Assignment> readSimple(final InputStream inputStream) throws Exception {
Serializer serializer = new Persister();
return serializer.read(AssignmentList.class, inputStream).getAssignments();
}
我几乎就是这样做的,只是使用 REST 服务,所以我不使用请求参数。
关于android - 从 http 服务器检索 xml 流 - android 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6747031/