前一篇给出了HttpGet的实例,这一篇给出HttpPost的实例。
public class HttpPostDemo extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); BufferedReader in = null; try { HttpClient client = new DefaultHttpClient(); HttpPost request = new HttpPost("http://mysomewebsite.com/services/doSomething.do"); List<NameValuePair> postParameters = new ArrayList<NameValuePair>(); postParameters.add(new BasicNameValuePair("username", "test")); postParameters.add(new BasicNameValuePair("password", "test1234")); UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity( postParameters); request.setEntity(formEntity); HttpResponse response = client.execute(request); in = new BufferedReader( new InputStreamReader( response.getEntity().getContent())); StringBuffer sb = new StringBuffer(""); String line = ""; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) { sb.append(line + NL); } in.close(); String result = sb.toString(); System.out.println(result); } catch(Exception e) { // Do something about exceptions } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
本文转自xyz_lmn51CTO博客,原文链接:http://blog.51cto.com/xyzlmn/1230791,如需转载请自行联系原作者