在我的应用程序中,我必须从服务器获取一些分配的列表。在服务器上,我有一个方法,比如fetchAssignments(int,String),它将两个值作为参数。
此函数将分配列表作为XML流返回。我知道如何连接到http服务器。但我没有得到如何在服务器上调用该方法并将这些参数传递给它。有谁能建议我做一个更好的方法......?
答案 0 :(得分:3)
您可以使用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服务,所以我不使用请求参数。
答案 1 :(得分:1)
根据语言,您可以通过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
}