android网络编程——http post

博客源址 android网络编程——http post


     前一篇给出了HttpGet的实例,这一篇给出HttpPost的实例。

[java]  view plain  copy
 print ?
  1. public class HttpPostDemo extends Activity {  
  2.     /** Called when the activity is first created. */  
  3.     @Override  
  4.     public void onCreate(Bundle savedInstanceState) {  
  5.         super.onCreate(savedInstanceState);  
  6.         setContentView(R.layout.main);  
  7.   
  8.         BufferedReader in = null;  
  9.         try {  
  10.             HttpClient client = new DefaultHttpClient();  
  11.             HttpPost request = new HttpPost("http://mysomewebsite.com/services/doSomething.do");  
  12.             List<NameValuePair> postParameters = new ArrayList<NameValuePair>();  
  13.             postParameters.add(new BasicNameValuePair("username""test"));  
  14.             postParameters.add(new BasicNameValuePair("password""test1234"));  
  15.             UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(  
  16.                     postParameters);  
  17.   
  18.             request.setEntity(formEntity);  
  19.             HttpResponse response = client.execute(request);  
  20.             in = new BufferedReader(  
  21.                     new InputStreamReader(  
  22.                             response.getEntity().getContent()));  
  23.   
  24.             StringBuffer sb = new StringBuffer("");  
  25.             String line = "";  
  26.             String NL = System.getProperty("line.separator");  
  27.             while ((line = in.readLine()) != null) {  
  28.                 sb.append(line + NL);  
  29.             }  
  30.             in.close();  
  31.   
  32.             String result = sb.toString();  
  33.             System.out.println(result);  
  34.         } catch(Exception e) {  
  35.             // Do something about exceptions  
  36.         } finally {  
  37.             if (in != null) {  
  38.                 try {  
  39.                     in.close();  
  40.                 } catch (IOException e) {  
  41.                     e.printStackTrace();  
  42.                 }  
  43.             }  
  44.         }  
  45.     }  
  46. }  

你可能感兴趣的:(android网络编程——http post)