Android ClientToSever Test

來源:互聯網
上載者:User

標籤:

實現用戶端上傳資料到伺服器端

  • 搭建伺服器,建立資料庫;
  • 建立PHP檔案;
  • 建立android工程;
1. 在本地下載XAMPP軟體後進行安裝和配置。
  • 配置XAMPP
     在瀏覽器裡輸入:localhost或者127.0.0.1即可看到XAMPP歡迎介面。
  • 修改phpMyAdmin配置
                 首先用相關軟體開啟位於D:/xampp/phpMyAdmin(安裝目錄)檔案夾中的config.inc.php檔案。      搜尋 $cfg[‘Servers‘][$i][‘auth_type‘]=‘config‘ 將其中的config(系預設值)更改為cookie儲存。
  • 登陸XAMPP首頁      
   通過預設首頁localhost左側的phpmyadmin導覽列進入phpmyadmin介面,可直接通過localhost/phpmyadmin/進入web登陸介面,輸入使用者名稱root後直接點擊登陸(密碼預設為空白)即可。
  • 建立管理員帳號及密碼
   首先進入許可權選項卡,點擊root帳號編輯其許可權,在最底端的只輸入相應的使用者名稱和密碼,其餘選項保持其預設值,確認後即可產生與原有root帳號相同許可權的新帳號
  • 測試組態是否完成  
   您可以在xampp目錄下的htdocs檔案夾下建立任意一個網站。例如:將測試檔案test.html放在.\xampp\htdocs\new路徑下,您就可以在瀏覽器的地址欄中輸入localhost/new/test.html來訪問這個檔案。
 

2. 在伺服器上建立資料庫

  • 瀏覽器開啟localhost/phpmyadmin/或者在XAMPP Control Panel面板上點擊MySQL的Admin按鈕進入網頁
  • 點擊“資料庫”選項卡進行資料哭建立,輸入資料庫名即可。
  • 在頁面左側點擊建立資料庫,即可進行資料表的建立。輸入建立資料表的名稱及欄位數,點擊執行即可建立。
3. 建立php檔案
     <?php
               $conn = mysql_connect("localhost"."siguoyi","140265");  // 串連伺服器
                if(!conn){
                      die("conn error");
                    }
     $db = mysql_select_db("buptant",$conn);   // 串連資料庫
     mysql_set_charset("utf8");
     
     $jsonString = $_POST("jsonString");
     $jsonString = str_replace(‘\"‘,‘"‘,$jsonString);
     $obj = json_decode($jsonString);
     $name = $obj->name;
     $age= $obj->age;
     $sex= $obj->sex;
     $school= $obj->school; // 對變數進行賦值
try {
     $sql = "INSERT INTO `student` (`name`,`age`,`sex`,`school`) VALUES (‘$name‘,‘$age‘,‘$sex‘,‘$school‘)";  // 插入資料
     $resultNew = mysql_query($sql,$conn);
     if(!$resultNew){
          echo "error";
     }else{
          echo "ok";
     }  // 查詢資料是否插入
$insert_id = mysql_insert_id();
} catch (Exception $e){ }
      ?>

4. 建立Android工程
  • 用json對資料進行打包上傳
String name = et_name.getText().toString();
                         String age = et_age.getText().toString();
                         String sex = et_sex.getText().toString();
                         String school = et_school.getText().toString();
                         try {
                              jsonObject.put("name", name);
                              jsonObject.put("age", age);
                              jsonObject.put("sex", sex);
                              jsonObject.put("school", school);
                         } catch (JSONException e) {
                              e.printStackTrace();
                         }
                         Log.v("uploaddata", "json" + jsonObject);
                         
  • 用httpClient進行通訊
   
public String upData() {
        String resultID = "-1";
        List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
        nameValuePair.add(new BasicNameValuePair("jsonString", jsonObject));
        InputStream inputStream = null;
        try {
            HttpClient httpClient = new DefaultHttpClient();
           
            HttpPost httpPost = new HttpPost(uploadDataURL);
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair, "UTF-8"));
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            inputStream = httpEntity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line = "";
            String result = "";
            while ((line = reader.readLine()) != null) {
                result = result + line;
            }
            resultID = result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultID;
    }
  • 在進行資料上傳時需新開線程
     new Thread(){
                              @Override
                              public void run() {
                                   // TODO Auto-generated method stub
                                   UploadData upload = new UploadData(Url, jsonObject);
                                   String result = upload.upData();
                                   Log.v("uploaddata", "result:" + result);
                              }
                              
                         }.start();
 

Android ClientToSever Test

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.