Android呼叫asp.net編寫的*.ashx(一般處理程式)獲取資料

暖楓無敵發表於2014-10-09
第一步: asp.net 編寫ssjc.ashx
<%@ WebHandler Language="C#" Class="ssjc" %>

using System;
using System.Web;
using System.Text;
using Syit.Common;
using System.Data;

public class ssjc : IHttpHandler {

    //Oracle資料庫連線類
    OracleDM dm = new OracleDM();
    
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        StringBuilder jsonBuilder = new StringBuilder();
        jsonBuilder.Append("{\"parent\":");
        jsonBuilder.Append("{\"children\":");
        jsonBuilder.Append("[");
        string strSQL = @"select t1.ID,t1.STCD,t1.NAME,t1.LGTD,t1.LTTD,t2.WATERLEVEL,t2.TIME from ST_CROSS_BRIDGE t1  left join
            (
            SELECT * FROM (SELECT ROW_NUMBER() OVER(PARTITION BY BRIDGEID ORDER BY TIME DESC ) lev,t.* from st_bridge_waterlevel t)
                               WHERE lev = 1 ORDER BY TIME DESC
            ) t2 on t1.stcd=t2.bridgeid";
        DataSet ds = dm.getsql(strSQL);
        foreach (DataRowView drv in ds.Tables[0].DefaultView)
        {
            jsonBuilder.Append("{\"id\":\"" + drv["ID"].ToString().Trim() + "\",\"depth\":\"" + (string.IsNullOrEmpty(drv["WATERLEVEL"].ToString().Trim())?"0" : drv["WATERLEVEL"].ToString().Trim()) + "\",\"name\":\"" + drv["NAME"].ToString().Trim() + "\",\"lgtd\":\"" + drv["LGTD"].ToString().Trim() + "\",\"lttd\":\"" + drv["LTTD"].ToString().Trim() + "\"},");
        }
        string jsonString = jsonBuilder.ToString().TrimEnd(',');
        jsonString+="]}}";
        context.Response.Write(jsonString);
    }

    public bool IsReusable
    {
        get
        {
            return true;
        }
    }

}




第二步:編寫SYIT_SSJC.java檔案繼承自Activity類

package cn.superyouth.www;


import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;



import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;


public class SYIT_SSJC extends Activity implements MKGeneralListener {

	private Toast mToast;
	boolean isError = false;
	List<Map<String,Object>> curData = new ArrayList<Map<String, Object>>(5);				// 當前頁面使用資料


	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.syit_ssjc);

	     // 開啟執行緒
	 		new Thread() {
	 			@Override
	 			public void run() {
	 				try {
	 					
	 				} catch (Exception e) {
	 					isError = true;
	 					System.out.println(e.toString());
	 				}
	 				handler.sendEmptyMessage(0); 				
	 			}
	 		}.start();
	}
	
	/**
	 * 用Handler來更新UI
	 */
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			if(isError){
				 //建立提示
				Dialog alertDialog = new AlertDialog.Builder(SYIT_SSJC.this). 
		                setTitle("提示"). 
		                setMessage("伺服器無響應,請稍候再試!"). 
		                setIcon(R.drawable.ic_launcher). 
		                create(); 
		        alertDialog.show();
			}else{
				new ReadHttpGet().execute("http://61.190.32.10/CityLowerRoadSys/ashx/ssjc.ashx");  //這裡是核心程式碼部分
			}
		}
	};
	
	// * 顯示Toast訊息
	private void showToast(String msg) {
		if (mToast == null) {
			mToast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
		} else {
			mToast.setText(msg);
			mToast.setDuration(Toast.LENGTH_SHORT);
		}
		mToast.show();
	}


	class ReadHttpGet extends AsyncTask<Object, Object, Object> {
		@Override
		protected Object doInBackground(Object... params) {
			HttpGet httpRequest = new HttpGet(params[0].toString());
			try {
				HttpClient httpClient = new DefaultHttpClient();
				HttpResponse httpResponse = httpClient.execute(httpRequest);
				if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
					String strResult = EntityUtils.toString(httpResponse
							.getEntity());
					return strResult;
				} else {
					return "請求出錯";
				}
			} catch (ClientProtocolException e) {
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}


		protected void onCancelled(Object result) {
			super.onCancelled();
		}

                 //取得的資料儲存在集合List<Map<String,Object>> curData 中,然後怎麼使用都可以了
		@Override
		protected void onPostExecute(Object result) {
			super.onPostExecute(result);
			try {
				// 建立一個JSON物件
				JSONObject jsonObject = new JSONObject(result.toString())
						.getJSONObject("parent");
				// 獲取某個物件的JSON陣列
				JSONArray jsonArray = jsonObject.getJSONArray("children");
				StringBuilder builder = new StringBuilder();
				for (int i = 0; i < jsonArray.length(); i++) {
					// 新建一個JSON物件,該物件是某個陣列裡的其中一個物件
					JSONObject jsonObject2 = (JSONObject) jsonArray.opt(i);
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("id", jsonObject2.getString("id"));
					map.put("name", jsonObject2.getString("name"));
					map.put("depth", jsonObject2.getString("depth"));
					map.put("lgtd", jsonObject2.getString("lgtd"));
					map.put("lttd", jsonObject2.getString("lttd"));
					curData.add(map);
				}
				
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}


		protected void onPreExecute() {
			Toast.makeText(getApplicationContext(), "開始HTTP GET請求",
					Toast.LENGTH_LONG).show();
		}


		protected void onProgressUpdate(Object... values) {
			super.onProgressUpdate(values);
		}
	}
}


相關文章