Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chaper 12 網路服務.

Similar presentations


Presentation on theme: "Chaper 12 網路服務."— Presentation transcript:

1 Chaper 12 網路服務

2 XAMPP & JSON

3 XAMPP簡介 XAMPP是一個把Apache網頁伺服器與PHP、Perl及MySQL集合在一起的安裝包,允許用戶可以在自己的電腦上輕易的建立網頁伺服器。

4 XAMPP安裝

5 XAMPP啟動

6 執行phpMyAdmin

7 php & mysql <?php $mysqli = new mysqli(' ','root','','cyut'); $mysqli->query("SET NAMES utf8"); $sql = "select * from student"; $result = $mysqli->query( $sql ); while ($row = $result->fetch_row() ) { echo "id:".$row[0]; echo ", name:".$row[1]; echo ", score:".$row[2]; echo ", ".$row[3]."<br>"; } $mysqli->close(); ?>

8 什麼是JSON JSON(JavaScript Object Notation)是一種羽量級的資料交換格式,易於閱讀和編寫,同時也易於機器解析和生成,非常適合於伺服器與用戶端的交互。JSON採用與程式設計語言無關的文本格式,但是也使用了類C語言的習慣,這些特性使JSON成為理想的資料交換格式。 和 XML 一樣,JSON 也是基於純文字的資料格式。JSON的資料格式非常簡單,您可以用 JSON 傳輸一個簡單的 String,Number,Boolean,也可以傳輸一個陣列,或者一個複雜的Object 物件。

9 JSON 的優點 相容性高 格式容易瞭解,閱讀及修改方便
支援許多資料格式 (number,string,booleans,nulls,array,associative array) 許多程式都支援函式庫讀取或修改 JSON 資料

10 object範例 { "name": "Jack B. Nimble", "at large": true, "grade": "A",
"format": { "type": "rect", "width": , "height": , "interlace": false, "framerate": 24 }

11 array範例 ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] [ [0, -1, 0], [1, 0, 0], [0, 0, 1] ]

12 Array與object範例 [ {"id":" ","name":"王小明", {"id":" ","name":"李大同", {"id":" ","name":"陳大華", ]

13 PHP, mysql與JSON範例 <?php
$mysqli = new mysqli(' ','root','','cyut'); $mysqli->query("SET NAMES utf8"); $sql = "select * from student"; $result = $mysqli->query( $sql ); while ($row = $result->fetch_assoc() ) { $output[] = $row; } echo json_encode($output); $mysqli->close(); ?>

14 Android的HTTP請求

15 Http request Web POST/GET Server APP engine DataBase Http response
JSON/XML… Client端發送一個Http request的請求,使用HttpPOST或是HttpGET的方式將參數傳遞到伺服器(Web Server),伺服器與後端資料庫連線將資料從資料庫撈出來,使用XML或是JSON的格式將資料庫的資料回傳給Client端,Client端再將資料解析後呈現在畫面上

16 發出HTTP請求 產生一個HttpClient類別物件 產生一個HTTP請求 設定HTTP請求參數 發出HTTP請求 處理請求結果
HttpGet HttpPost 設定HTTP請求參數 names/values 發出HTTP請求 處理請求結果 專案中的AndroidManifest.xml檔案中需加入 <uses-permission android:name="android.permission.INTERNET"/>

17 DefaultHttpClient類別 實作HttpClient的一個類別
處理HTTP請求的cookies, authentication, connection management等 方法 HttpResponse execute(HttpUriRequest request) 執行HTTP請求 HttpClient client = new DefaultHttpClient();

18 HttpGet類別 建構子 HttpGet() HttpGet(URI uri) HttpGet(String uri)
HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(" HttpGET的方式為直接在需要建立連線的網址後面加上所需帶入的參數 HttpResponse response = client.execute(get);

19 讀取網頁字串 try { HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(" HttpResponse response = client.execute(get); String jsonText = EntityUtils.toString(response.getEntity()); showJSON(jsonText); } catch (Exception e) { e.printStackTrace();

20 解析JSON資料 try { JSONArray array = new JSONArray(jsonText);
for (int i = 0;i<array.length(); i++) { JSONObject obj = array.getJSONObject(i); String id = obj.getString("id"); String name = obj.getString("name"); int score = obj.getInt("score"); String = obj.getString(" "); } } catch (Exception e) { e.printStackTrace();

21 加入HTTP請求參數(Name/Value)
HttpGet method = new HttpGet( " client.execute(method); The length of a URL should be kept below 2048 characters. use HTTP POST 使用HttpGet類別將需要建立連線的網址在問號後面帶入參數以及參數的值

22 HttpPost類別 建構子 方法 HttpPost() HttpPost(URI uri) HttpPost(String uri)
void setEntity(UrlEncodedFormEntity entity) 設定請求參數 HttpPOST的方式就如同網頁表單傳送的方式,將需要傳送的參數和參數的值以NameValue的方式封裝在連線的請求中

23 HttpPost傳遞參數 HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost( List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(“name”, “Jack")); UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params); post.setEntity(formEntity); HttpResponse response = client.execute(post);

24 PHP, mysql與JSON範例2 <?php
$mysqli = new mysqli(' ','root','','cyut'); $mysqli->query("SET NAMES utf8"); $name = $_REQUEST["name"]; $sql = "select * from student where name='$name'"; $result = $mysqli->query( $sql ); while ($row = $result->fetch_assoc() ) { $output[] = $row; } echo json_encode($output); $mysqli->close(); ?>

25 傳送參數及讀取網頁JSON try { HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(" List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("ID","A002")); UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params); post.setEntity(formEntity); HttpResponse response = client.execute(post); String jsonText = EntityUtils.toString(response.getEntity()); showJSON(jsonText); } catch (Exception e) { e.printStackTrace(); }

26 主執行緒與網路操作 從Android 3.0開始,Thread Policy加強了限制,只要嘗試在主執行緒中進行網路操作,就會產生NetworkOnMainThreadException這個錯誤。 (Android 2.3的裝置運行正常,在Android 4.0的裝置就會出現。)

27 主執行緒與網路操作 解決方式有下列兩種方式:
1.在onCreate()中加入下列程式,透過StrictMode重新設定ThreadPolicy。 2.把網路操作從主執行緒中移走,你可以自己再開一個Thread,或使用AsyncTask來執行。

28 StrictMode.ThreadPolicy
policy = new StrictMode.ThreadPolicy .Builder() .permitAll() .build(); StrictMode.setThreadPolicy(policy);    

29 getHttpContent()方法 public String getHttpContent() { try {
HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(" List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("ID","A002")); UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params); post.setEntity(formEntity); HttpResponse response = client.execute(post); String jsonText = EntityUtils.toString(response.getEntity()); return (jsonText); } catch (Exception e) { e.printStackTrace(); } return "";

30 Thread & Handler String jsonText; Handler handler = new Handler();
class Messager implements Runnable { @Override public void run() { showJSON(jsonText); } @Override public void onClick(View v) { new Thread() { jsonText = getHttpContent(); handler.post(new Messager() ); }.start();

31 介面物件 ListView LearnLayout(Hor) ImageView LearnLayout(Ver)
TaxtView1(放cities) TextView2(放mayor) public class MainActivity extends Activity { String[] cities = {"新北市","台北市","台中市","台南市","高雄市"}; String[] mayors = {"朱立倫","柯文哲","林佳龍","賴清德","陳菊"}; int[] pics={R.drawable.newpei,R.drawable.taipei,R.drawable.taichung, R.drawable.tainan,R.drawable.kaohsiung}; List<Map<String,Object>> data = new ArrayList<Map<String,Object>>(); ListView listView1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); for(int i=0;i<cities.length;i++) { Map<String,Object> map = new HashMap<String,Object>(); map.put("city", cities[i]); map.put("mayor", mayors[i]); map.put("pic",pics[i]); data.add(map); } listView1=(ListView)findViewById(R.id.listView1); SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.list_item, new String[]{"city","mayor","pic"}, new int[]{R.id.cities,R.id.mayor,R.id.pic}); listView1.setAdapter(adapter); /*List<Map<String,String>> data = new ArrayList<Map<String,String>>(); ListView listView1;*/ //沒有加入圖片的語法 /* Map<String,String> map = new HashMap<String,String>(); */ //↑沒有加入圖片的語法 /*SimpleAdapter adapter = new SimpleAdapter(this, android.R.layout.simple_list_item_2, new String[]{"city","mayor"}, new int[]{android.R.id.text1,android.R.id.text2});*/ //↑沒有圖片的 備忘錄

32 介面物件 dialog Button 備忘錄 程式內容為多選(勾選式清單) //備註部分為單選(RadioButton)
package com.example.dialog; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.SparseBooleanArray; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; public class MainActivity extends ActionBarActivity implements OnClickListener,DialogInterface.OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.button1).setOnClickListener(this); } public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return super.onOptionsItemSelected(item); String[] data = {"Copy","Cut","Paste"}; boolean[] checked = {true,false,true}; public void onClick(View v) { // TODO Auto-generated method stub new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle("訊息視窗") //.setMessage("This is a test ! ") //.setSingleChoiceItems(data,2,null) //單選 .setMultiChoiceItems(data, checked, null) //.setItems(data,this) .setPositiveButton("Yes", this) //.setNegativeButton("No",this) .setNeutralButton("Cancel", this) .show(); public void onClick(DialogInterface dialog, int which) { /* switch(which){ case -1: setTitle("Yes"); //正面 break; case -2: setTitle("No"); //反面 case -3: setTitle("Cancel"); //中性 default: setTitle(data[which]); } */ /* int pos = ((AlertDialog)dialog).getListView().getCheckedItemPosition(); setTitle(data[pos]); */ // 單選 SparseBooleanArray checks = ((AlertDialog)dialog).getListView().getCheckedItemPositions(); String s = ""; for(int i=0;i<checks.size();i++){ if(checks.get(i)) s+= data[i]+" "; setTitle(s); 備忘錄 程式內容為多選(勾選式清單) //備註部分為單選(RadioButton)

33 介面物件 資料庫(json) TextView ; EditText ; 備忘錄
package com.example.mm_065.jsontest2; import android.os.StrictMode; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.TextView; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; public class MainActivity extends ActionBarActivity implements View.OnClickListener { TextView t1; EditText e1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy .Builder() .permitAll() .build(); StrictMode.setThreadPolicy(policy); t1 = (TextView)findViewById(R.id.textView); e1 = (EditText)findViewById(R.id.editText); findViewById(R.id.button).setOnClickListener(this); } public void onClick(View v) { try { HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(" List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("ID", e1.getText().toString() )); UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params); post.setEntity(formEntity); HttpResponse response = client.execute(post); String jsonText = EntityUtils.toString(response.getEntity()); showJSON(jsonText); catch (Exception e) { e.printStackTrace(); public void showJSON(String jsonText) { String s = ""; JSONArray array = new JSONArray(jsonText); for (int i=0; i<array.length(); i++) JSONObject obj = array.getJSONObject(i); String id = obj.getString("ID"); String name = obj.getString("name"); int score = obj.getInt("score"); String = obj.getString(" "); s += "ID:"+id+" name:"+name+" score:"+score+" "+ +"\n"; t1.setText(s); } catch(Exception e) { e.printStackTrace(); public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return super.onOptionsItemSelected(item); 備忘錄


Download ppt "Chaper 12 網路服務."

Similar presentations


Ads by Google