本例介绍在Android中利用HttpPost向服务器提交数据,并获取结果(字符串形式)的方法。服务器上获取提交来的参数由该服务器平台所使用的语言决定,如ASP.NET中可使用Request.Form["name"]获取,PHP中使用$_post["name"]。
public String GetRemoteData() { try { List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("name", "tiger")); params.add(new BasicNameValuePair("age", "99")); HttpPost post = new HttpPost("http://www.corp.com/send.ashx"); post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); HttpResponse response = new DefaultHttpClient().execute(post); return EntityUtils.toString(response.getEntity()); }catch(UnsupportedEncodingException e){ return "UnsupportedEncodingException"; }catch(IOException e) { return "IOException"; }catch(NetworkOnMainThreadException e){ return "NetworkOnMainThreadException"; }catch(Exception e){ return "Error: " + e.toString(); } }