Android端與Java端的資料互動
Android從第三方專案獲取資料通常使用這兩種方式
1,xml格式的資料互動(對xml進行解析獲取資料)
2,json格式的資料互動(對json格式資料進行解析,使用HttpClient技術訪問後臺程式碼)
HttpClient的使用步驟
3. HttpClient的使用步驟
3.1 建立HttpClient物件
HttpClient httpClient = new DefaultHttpClient();
3.2 建立HttpGet(或HttpPost)物件
HttpGet HttpGet = new HttpGet("http://www.baidu.com");
HttpPost httpPost = new HttpPost("http://www.baidu.com");
3.3 新增引數(可選)
setParams(HttpParams params)//HttpGet和HttpPost共有
setEntity(HttpEntity entity)//HttpPost獨有
3.4 傳送GET(或POST)請求,並獲得響應
HttpResponse httpResponse = httpClient.execute(HttpUriRequest request);
注1:HttpUriRequest為HttpGet和HttpPost的父類
注2:需要新增允許網路訪問許可權,不然會報錯“java.lang.SecurityException: Permission denied (missing INTERNET permission?)”
<uses-permission android:name="android.permission.INTERNET" />
注3:如果地址錯誤,或伺服器未開戶,HttpClient這SB會等待N久(>24小時)。
Request sent資料請求時間;Waiting資料響應時間,
注:多注意Request sent和Waiting時間的長短,如這兩種時間超時明顯過長可能是第三方資料發生了地址性的變化
所以請記得設定超時時間,所以請記得設定超時時間,所以請記得設定超時時間
所以請記得設定超時時間,所以請記得設定超時時間,所以請記得設定超時時間
所以請記得設定超時時間,所以請記得設定超時時間,所以請記得設定超時時間
另外HttpClient版本不一樣,程式碼也不一樣。下面的4.0版本的寫法
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 2000);// 連線時間
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 2000);// 資料傳輸時間
3.5 處理響應
3.5.1 響應狀態碼(200)
httpResponse.getStatusLine().getStatusCode()
3.5.2 響應頭
getAllHeaders()/getHeaders(String name)
3.5.3 響應內容
HttpEntity httpEntity = httpResponse.getEntity();//此物件包含伺服器的響應內容
String result = EntityUtils.toString(httpEntity);
下面我舉一個例項來講述Android與Java端的資料互動:
1.這裡我使用一個已經封裝好的HttpClient物件Post請求
package com.example.jack_and06; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpEntity; 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.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.util.EntityUtils; import android.os.AsyncTask; /** * 封裝 HttpClient物件POST請求 * */ public class HttpClientPost implements Serializable { private static final long serialVersionUID = 1777547416049652217L; private static HttpClient httpClient = new DefaultHttpClient(); static { httpClient.getParams().setParameter( CoreConnectionPNames.CONNECTION_TIMEOUT, 2000);// 連線時間 httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 3000);// 資料傳輸時間 } // 字符集 private static String encoding = "UTF-8"; // 伺服器地址+埠號+專案名 private static String basePath = "http://192.168.43.157:8080/blog_limit/"; // 子控制器的路徑 private String path; // 儲存請求中的引數 private List<NameValuePair> params = new ArrayList<NameValuePair>();; public HttpClientPost(String path) { super(); this.path = path; } /** * 向POST請求中新增引數 * * @param name * @param value */ public void addParam(String name, String value) { if (value == null) { params.add(new BasicNameValuePair(name, "")); } else { params.add(new BasicNameValuePair(name, value)); } } /** * 提交POST請求 */ @SuppressWarnings("unchecked") public void submit(final HttpClientPost.Callback callback) { /** * 呼叫類物件excute()方法屬性 */ new AsyncTask() { private String json; @Override protected Object doInBackground(Object... args) { try { // 1. 建立HttpClient物件 // 2. 建立HttpGet(或HttpPost)物件 HttpPost httpPost = new HttpPost(basePath + path); // 3. 向POST請求中新增引數(可選) if (0 != params.size()) { HttpEntity paramEntity = new UrlEncodedFormEntity( params, encoding); httpPost.setEntity(paramEntity); } // 4. 傳送POST請求,並獲得響應 HttpResponse httpResponse = httpClient.execute(httpPost); // 5. 處理響應 if (200 == httpResponse.getStatusLine().getStatusCode()) { HttpEntity responseEntity = httpResponse.getEntity();// 此物件包含伺服器的響應內容 this.json = EntityUtils.toString(responseEntity); } } catch (Exception e) { throw new RuntimeException(e); } return null; } protected void onPostExecute(Object result) { callback.execute(this.json); } }.execute(); } //建立內部回撥函式,使用二十三種設計模式之策略模式 、 //(作用:在方法或類中已經完成了對應的功能,然後在呼叫方根據自己的需求去處理結果) public static interface Callback { void execute(String json); } }
2.建立一個Android佈局
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <Button android:id="@+id/bt_main_add" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="新增" /> <Button android:id="@+id/bt_main_edit" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="修改" /> <Button android:id="@+id/bt_main_del" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="刪除" /> <Button android:id="@+id/bt_main_load" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="查單個" /> <Button android:id="@+id/bt_main_list" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="查全部" /> </LinearLayout>
3.在Activity類中實現資料的互動
package com.example.jack_and06; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.util.List; import java.util.Map; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private Button bt_main_add; private Button bt_main_edit; private Button bt_main_del; private Button bt_main_load; private Button bt_main_list; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //查詢控制元件 findViews(); //繫結監聽器 bt_main_add.setOnClickListener(this); bt_main_edit.setOnClickListener(this); bt_main_del.setOnClickListener(this); bt_main_load.setOnClickListener(this); bt_main_list.setOnClickListener(this); } private void findViews() { bt_main_add = (Button) findViewById(R.id.bt_main_add); bt_main_edit = (Button) findViewById(R.id.bt_main_edit); bt_main_del = (Button) findViewById(R.id.bt_main_del); bt_main_load = (Button) findViewById(R.id.bt_main_load); bt_main_list = (Button) findViewById(R.id.bt_main_list); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.bt_main_add: add(); break; case R.id.bt_main_edit: edit(); break; case R.id.bt_main_del: del(); break; case R.id.bt_main_load: load(); break; case R.id.bt_main_list: list(); break; } } private void add() { Log.i("test", "add..."); } private void edit() { Log.i("test", "edit..."); } private void del() { Log.i("test", "del..."); } private void load() { Log.i("test", "load..."); } private void list() { Log.i("test", "list..."); //建立httpClientPost物件輸入資料路徑 HttpClientPost httpClientPost = new HttpClientPost("userAction.action"); httpClientPost.addParam("methodName","blogUserList"); httpClientPost.submit(new HttpClientPost.Callback() { @Override public void execute(String json) { Log.i("json",json);//LogCat輸出資料 ObjectMapper om = new ObjectMapper(); try { Map<String,Object> map = om.readValue(json, Map.class); List rows = (List) map.get("rows"); Map<String,Object> o = (Map<String, Object>) rows.get(0); Log.i("username",o.get("username").toString()); } catch (IOException e) { e.printStackTrace(); } } }); } }
最後我們使用模擬器來檢視所查詢到的Java資料
Android應用在LogCat輸出資料資訊