eclipse 連線 Android 獲取資料庫資料
阿新 • • 發佈:2018-12-10
package com.example.t211_05; 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.171:8089/Shu_easyui"; // 子控制器的路徑 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) { 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); } }
//注意獲取本機的埠號,不要使用localhost