Android 實現Post向伺服器提交資料

來源:互聯網
上載者:User

 

Android 實現Post向伺服器提交資料

 熟悉web編程的都很瞭解get和post這兩種傳遞表單資料的方法。

 這裡不具體介紹get和post的區別,如需瞭解請參考:http://www.bkjia.com/kf/201112/114558.html

 所謂的get傳遞資料也是我們最常見的一種,如http://127.0.0.1/index.php?param=androidyue,這種方式直接顯示在url中,因此很不安全,

 而使用post傳遞資料則不會直接暴露出來,相對來說更加安全一些。post傳遞也需要key和value。

 以下是android程式範例程式碼:

 

package com.google.code.cakedroid.demo;

 

 

 

 

 import java.util.ArrayList;

 import java.util.List;

 

 

 import org.apache.http.HttpResponse;

 import org.apache.http.NameValuePair;

 import org.apache.http.client.entity.UrlEncodedFormEntity;

 import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;

 import org.apache.http.client.methods.HttpPost;

 import org.apache.http.impl.client.DefaultHttpClient;

 import org.apache.http.message.BasicNameValuePair;

 import org.apache.http.protocol.HTTP;

 import org.apache.http.util.EntityUtils;

 

 

 import com.google.code.cakedroid.R;

 

 

 import android.app.Activity;

 import android.os.Bundle;

 import android.view.View;

 import android.widget.Button;

 import android.widget.TextView;

 

 

 public class PostMethodDemoActivity extends Activity{

     //declare the variables

     private TextView tvResult;

     private Button btnClick;

     

     @Override

     protected void onCreate(Bundle savedInstanceState) {

         super.onCreate(savedInstanceState);

         setContentView(R.layout.main);

         this.initViews();

     }

     

     /*

      * initialize necessary views

      */

     private void initViews(){

         this.initButtons();

         this.initTextViews();

     }

     

     /*

      * initialize necessary textviews

      */

     private void initTextViews(){

         this.tvResult=(TextView)this.findViewById(R.id.tvResult);

     }

     

     /*

      * initialize necessary buttons

      */

     private void initButtons(){

         this.btnClick=(Button)this.findViewById(R.id.btnClick);

         this.btnClick.setOnClickListener(new View.OnClickListener() {

             

             @Override

             public void onClick(View arg0) {

                 // TODO Auto-generated method stub

                 postData();

             }

         });

     }

     

     /*

      * post data to remote host

      */

     private void postData(){

         String destUrl="http://10.0.2.2/form_handler.php";

         //instantiate HttpPost object from the url address

         HttpEntityEnclosingRequestBase httpRequest =new HttpPost(destUrl);

         //the post name and value must be used as NameValuePair

         List <NameValuePair> params=new ArrayList<NameValuePair>();

         params.add(new BasicNameValuePair("param","I have posted you the data"));

         try{

          httpRequest.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));

          //execute the post and get the response from servers

          HttpResponse httpResponse=new DefaultHttpClient().execute(httpRequest);

           

          if(httpResponse.getStatusLine().getStatusCode()==200){

           //get the result

           String strResult=EntityUtils.toString(httpResponse.getEntity());

           tvResult.setText(strResult);

          }else{

           tvResult.setText("Error Response"+httpResponse.getStatusLine().toString());

          }

         }catch(Exception e){

             System.out.println("error occurs");

         }

     }

 }

 

 

伺服器斷php代碼:

 

<?php

     if(isset($_POST['param'])){

         echo $_POST['param'].'  I received the data';

     }

 ?>

 

 

注意:如果如需正常訪問,請在manifest.xml中添加internet存取權限。

 

摘自BossDarcy的專欄

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.