標籤:
實現用戶端上傳資料到伺服器端
- 搭建伺服器,建立資料庫;
- 建立PHP檔案;
- 建立android工程;
1. 在本地下載XAMPP軟體後進行安裝和配置。
在瀏覽器裡輸入:localhost或者127.0.0.1即可看到XAMPP歡迎介面。
首先用相關軟體開啟位於D:/xampp/phpMyAdmin(安裝目錄)檔案夾中的config.inc.php檔案。 搜尋 $cfg[‘Servers‘][$i][‘auth_type‘]=‘config‘ 將其中的config(系預設值)更改為cookie儲存。
通過預設首頁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工程
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);
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