在我的应用程序中,我必须从服务器获取一些分配的列表。在服务器上,我有一个方法,比如fetchAssignments(int,String),它接受两个值作为参数。
- 周期(今天、本月或本周)-整数
- 用户id - String
函数以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();
}
然后可以使用"Simple"(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服务,所以我不使用请求参数
根据语言的不同,您可以通过URL HTTP请求或使用POST传递参数。在类的构造函数中(假设它是一个网页?. php ?.aspx?)检索这些值并将它们传递给上面提到的方法?
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/getfeed.php");
InputSource inStream = new InputSource();
try {
// Add data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("period", period));
nameValuePairs.add(new BasicNameValuePair("userid", user_id));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
String xmlString = EntityUtils.toString(r_entity);
xmlString = xmlString.trim();
InputStream in = new ByteArrayInputStream(xmlString.getBytes("UTF-8"));
if(xmlString.length() != 0){
inStream.setByteStream(in);
PARSE_FLAG = true;
}
else
{
PARSE_FLAG = false;
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}