編輯:Android 開發實例
最近在做的專案,後端採用 WCF 接收 Android 手機拍照上傳的圖片,並把其他參數一併存進伺服器。剛好把近期學的 WCF 派上用場,原以為是個簡單功能應該手到擒來,沒想到過程中踩了不少坑,網上翻找許久仍無解,最後靠著「把資料流分段寫入、後端再解析這個流」的方式才成功達陣。後端運用 WCF 中的 REST 來接收資料——REST 其實不難,不熟的朋友可以先上網快速了解一下。在動手前,先複習幾個本次會用到的理論知識。
一、理論知識
由於底層協議特性所限,WCF 的流模式僅支援以下四種:1. BasicHttpBinding 2. NetTcpBinding 3. NetNamedPipeBinding 4. WebHttpBinding。
1. 設定 TransferMode。它支援四種模式(Buffered、Streamed、StreamedRequest、StreamedResponse),請依實際情況設為三種 Stream 模式之一。
2. 修改 MaxReceivedMessageSize。該值預設僅 64k,因此當傳輸資料超過 64k 時便會拋出 CommunicationException 異常。
3. 修改 receiveTimeout 與 sendTimeout。大資料傳輸耗時較長,需調高這兩個值以免超時。
二、問題剖析
WCF 若以 Stream 作為參數,就只能有這唯一一個參數,不能再帶其他參數——這正是本次要重點攻克的難題。可我們除了圖片,手機還得帶上其他參數,最後決定讓手機端把參數與圖片一起寫進 Stream,再由後端 WCF 解析這個參數流。
以下是約定好的 Stream 格式,傳過來的 Stream 共分三段:參數資訊長度 參數資訊 圖片。
1. 參數資訊長度(1 位元組):存放參數資訊的長度(以位元組為單位)。
2. 參數資訊:除圖片外的參數,以 JSON 形式存放,例如 {"type":"jpg","EmployeeID":"12","TaskID":"13"}。
3. 圖片:圖片的位元組。
三、WCF 端程式碼
1. 先定義一個 WCF 契約。由於採用 REST(命名空間 ServiceModel.Web 之下),契約 IAndroidInfo 內容如下,以 POST 方式接收:
- using System.ServiceModel;
- using System.Runtime.Serialization;
- using System.ServiceModel.Web;
- import System.IO;
- namespace Coreius.CEIMS.AndroidInterface
- {
- [ServiceContract]
- public interface IAndroidInfo
- {
- [WebInvoke(UriTemplate = "GpsUpFile", Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json,
- ResponseFormat = WebMessageFormat.Json)]
- bool GpsUpFile(Stream ImageContext);
- }
- }
2. 依契約實作服務內容:接收一個流的參數,先把這個 Stream 轉成位元組,再依先前約定取出第一個位元組的值,據此界定另外三個參數的位元組長度,接著透過 JSON 轉換把三個參數值取出,剩下的位元組便是手機拍的照片,將它存進伺服器 D 槽的資料夾。
- using System.Linq;
- using System.Text;
- using System.ServiceModel;
- import System.ServiceModel.Web;
- import System.IO;
- import Newtonsoft.Json;
- namespace Coreius.CEIMS.AndroidService
- {
- public class AndroidInfoService:IAndroidInfo
- {
- public bool GpsUpFile(Stream ImageContext)
- {
- byte[] m_Bytes = ReadToEnd(ImageContext);
- int len = (int)m_Bytes[0];
- byte[] data = m_Bytes.Skip(1).Take(len).ToArray();
- string Jsonstr = System.Text.Encoding.Default.GetString(data);
- JsonModel item = JsonConvert.DeserializeObject<JsonModel>(Jsonstr);
- string ImageType=item.type;
- string EmployeeID=item.EmployeeID;
- string TaskID=item.TaskID;
- byte[] Imagedata = m_Bytes.Skip(1 + len).ToArray();
- string DiskName = "d:";
- string FileAddress = "\\UpLoad\\";
- string LocationAddress = DiskName + FileAddress;
- if (!DirFileHelper.IsExistDirectory(LocationAddress))
- {
- DirFileHelper.CreateDirectory(LocationAddress);
- }
- string ImageName = DateTime.Now.ToString("yyyyMMddhhmmss.") + ImageType;
- string ImagePath = LocationAddress + ImageName;
- if (!File.Exists(ImagePath))
- {
- try
- {
- System.IO.File.WriteAllBytes(ImagePath, Imagedata);
- ImageContext.Close();
- return true;
- }
- catch
- {
- return false;
- }
- }
- else
- {
- return false;
- }
- }
- }
- }
上面的程式碼用到幾個方法,例如把流轉成位元組、把 JSON 轉成物件等,程式碼如下:
- public byte[] ReadToEnd(System.IO.Stream stream)
- {
- long originalPosition = 0;
- if (stream.CanSeek)
- {
- originalPosition = stream.Position;
- stream.Position = 0;
- }
- try
- {
- byte[] readBuffer = new byte[4096];
- int totalBytesRead = 0;
- int bytesRead;
- while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
- {
- totalBytesRead += bytesRead;
- if (totalBytesRead == readBuffer.Length)
- {
- int nextByte = stream.ReadByte();
- if (nextByte != -1)
- {
- byte[] temp = new byte[readBuffer.Length * 2];
- Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
- Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
- readBuffer = temp;
- totalBytesRead++;
- }
- }
- }
- byte[] buffer = readBuffer;
- if (readBuffer.Length != totalBytesRead)
- {
- buffer = new byte[totalBytesRead];
- Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead);
- }
- return buffer;
- }
- finally
- {
- if (stream.CanSeek)
- {
- stream.Position = originalPosition;
- }
- }
- }
- public class JsonModel
- {
- public string type { get; set; }
- public string EmployeeID { get; set; }
- public string TaskID { get; set; }
- }
3. 新建一個文字檔,把副檔名改成 .svc 作為服務發佈端(宿主為 IIS)供 Android 手機呼叫,並寫入以下內容:
- <%@ ServiceHost Language="C#" Debug="true" Service="Coreius.CEIMS.AndroidService.AndroidInfoService" %>
接著修改 Web.config 的內容:
- <?xml version="1.0" encoding="utf-8"?>
- <configuration>
- <appSettings>
- <add key="ConnectionString" value="server=127.0.0.1;database=Coreius;uid=sa;pwd=admin"/>
- </appSettings>
- <system.web>
- <compilation debug="true" targetFramework="4.0" />
- </system.web>
- <system.serviceModel>
- <behaviors>
- <endpointBehaviors>
- <behavior name="webHttp">
- <webHttp helpEnabled="true"/>
- </behavior>
- </endpointBehaviors>
- <serviceBehaviors>
- <behavior name="MapConfigBehavior">
- <!-- 為避免洩漏元數據信息,請在部署前將以下值設置為 false 並刪除上面的元數據終結點 -->
- <serviceMetadata httpGetEnabled="true"/>
- <!-- 要接收故障異常詳細信息以進行調試,請將以下值設置為 true。在部署前設置為 false 以避免洩漏異常信息 -->
- <serviceDebug includeExceptionDetailInFaults="true"/>
- <dataContractSerializer maxItemsInObjectGraph="2147483647"/>
- </behavior>
- </serviceBehaviors>
- </behaviors>
- <bindings>
- <webHttpBinding>
- <binding name="webHttpBindConfig" receiveTimeout="00:30:00" sendTimeout="00:30:00" maxReceivedMessageSize="104857600" transferMode="Streamed">
- <readerQuotas maxStringContentLength="2147483647" maxArrayLength="2147483647"/>
- <security mode="None"></security>
- </binding>
- </webHttpBinding>
- </bindings>
- <services>
- <service name="Coreius.CEIMS.AndroidService.AndroidInfoService" behaviorConfiguration="MapConfigBehavior">
- <endpoint binding="webHttpBinding" contract="Coreius.CEIMS.AndroidInterface.IAndroidInfo" bindingConfiguration="webHttpBindConfig"
- behaviorConfiguration="webHttp"/>
- </service>
- </services>
- </system.serviceModel>
- </configuration>
此處有幾點要特別注意:
(1)此處採用的是 webHttpBinding,因此一定要設定 behaviorConfiguration 才會生效,其中 helpEnabled="true" 是為了能在發佈後查看說明資訊:
- <behavior name="webHttp">
- <webHttp helpEnabled="true"/>
- </behavior>
(2)為實現大檔上傳,需如下設定最大值,其中 security 是設定訪問服務的認證(此處設為不認證),transferMode 則是設定採用流的模式:
- <webHttpBinding>
- <binding name="webHttpBindConfig" receiveTimeout="00:30:00" sendTimeout="00:30:00" maxReceivedMessageSize="104857600" transferMode="Streamed">
- <readerQuotas maxStringContentLength="2147483647" maxArrayLength="2147483647"/>
- <security mode="None"></security>
- </binding>
- </webHttpBinding>
完成上述程式碼後,就能在伺服器 IIS 上部署這個 WCF 服務了。
四、Android 端程式碼
由於手機端程式碼由另一位朋友撰寫,這裡把大體程式碼貼出來,原理就是把參數與圖片寫進流(圖片先進行壓縮處理),再呼叫部署好的 WCF 服務。
程式碼一:因為伺服器並非公用,下面的 IP 我隨便改了個;
- private void toUploadFile(File file) throws FileNotFoundException {
- String result = null;
- requestTime= 0;
- int res = 0;
- long requestTime = System.currentTimeMillis();
- long responseTime = 0;
- //封裝參數信息
- JSONObject jsonObject = new JSONObject();
- try {
- jsonObject.put("EmployeeID", MainActivity.guid);
- jsonObject.put("TaskID", "e52df9b4-ee3b-46c5-8387-329b76356641");
- String[] type = file.getName().split("\\.");
- jsonObject.put("type", type[type.length-1]);
- } catch (JSONException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- /**上傳文件*/
- HttpParams httpParameters = new BasicHttpParams();
- HttpConnectionParams.setConnectionTimeout(httpParameters, 1000*30);
- HttpConnectionParams.setSoTimeout(httpParameters, 1000*30);
- HttpConnectionParams.setTcpNoDelay(httpParameters, true);
- String path = PictureUtil.zipNewImage(file); //壓縮文件後返回的文件路徑
- byte[] bytes = null;
- InputStream is;
- File myfile = new File(path);
- try {
- is = new FileInputStream(path);
- bytes = new byte[(int) myfile.length()];
- int len = 0;
- int curLen = 0;
- while ((len = is.read(bytes)) != -1) {
- curLen += len;
- is.read(bytes);
- }
- is.close();
- } catch (FileNotFoundException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- byte[] updata = GpsImagePackage.getPacket(jsonObject.toString(), bytes); //參數與文件封裝成單個數據包
- HttpClient httpClient = new DefaultHttpClient(httpParameters);
- HttpPost httpPost = new HttpPost(MyUrl.upload_file);
- HttpResponse httpResponse;
- //單個文件流上傳
- InputStream input = new ByteArrayInputStream( updata );
- InputStreamEntity reqEntity;
- reqEntity = new InputStreamEntity(input, -1);
- reqEntity.setContentType("binary/octet-stream");
- reqEntity.setChunked(true);
- httpPost.setEntity(reqEntity);
- try {
- httpResponse = httpClient.execute(httpPost);
- responseTime = System.currentTimeMillis();
- this.requestTime = (int) ((responseTime-requestTime)/1000);
- res = httpResponse.getStatusLine().getStatusCode();
- if (httpResponse.getStatusLine().getStatusCode() ==200) {
- Log.e(TAG, "request success");
- Log.e(TAG, "result : " + result);
- return;
- } else {
- Log.e(TAG, "request error");
- sendMessage(UPLOAD_SERVER_ERROR_CODE, "上傳失敗:code=" + res);
- return;
- }
- } catch (ClientProtocolException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
程式碼二:
- package com.anthony.util;
- public class GpsImagePackage {
- public GpsImagePackage() {
- // TODO Auto-generated constructor stub
- }
- //封裝字節數組與參數
- public static byte[] getPacket(String json,byte[] image){
- byte[] jsonb = json.getBytes();
- int length = image.length + jsonb.length;
- System.out.println(image.length +", "+ jsonb.length);
- byte[] bytes = new byte[length+1];
- byte[] lengthb = InttoByteArray(jsonb.length, 1);
- System.arraycopy(lengthb, 0, bytes, 0, 1);
- System.arraycopy(jsonb, 0, bytes, 1, jsonb.length);
- System.arraycopy(image, 0, bytes, 1+jsonb.length, image.length);
- return bytes;
- }
- //將int轉換為字節數組
- public static byte[] InttoByteArray(int iSource, int iArrayLen) {
- byte[] bLocalArr = new byte[iArrayLen];
- for ( int i = 0; (i < 4) && (i < iArrayLen); i++) {
- bLocalArr[i] = (byte)( iSource>>8*i & 0xFF );
- }
- return bLocalArr;
- }
- // 將byte數組bRefArr轉為一個整數,字節數組的低位是整型的低字節位
- public static int BytestoInt(byte[] bRefArr) {
- int iOutcome = 0;
- byte bLoop;
- for ( int i =0; i<bRefArr.length ; i++) {
- bLoop = bRefArr[i];
- iOutcome+= (bLoop & 0xFF) << (8 * i);
- }
- return iOutcome;
- }
- }
五、運行效果:
用 ListView 打造專業級表格界面(股票行情實例)
ListView 表面上是個列表,但只要願意在 item 布局上下功夫,完全可以做成一個像樣的表格。本文以股票行情為例:紅色代表上漲,綠色代表下跌,表頭固定不動,列表獨立
Android 手機衛士(十三):實現設置界面的一個條目布局
從本文開始,我們會一步步把功能列表補齊。 一、為九宮格註冊點擊事件 要讓九宮格中的條目可以點擊,得先註冊監聽: // 注冊九宮格單個條目的點擊事件 gv_hom
Android 選單機制(三):PopupMenu 彈出式選單實作
選單系列的最後一篇,來看 PopupMenu。與 Options Menu 佔據標題欄、Context Menu 綁定長按不同,PopupMenu 是「錨定在某個 Vie
Android 登入畫面實作:密碼遮罩、錯誤提示與三次鎖定
幾乎每個需要使用者帳號的 App,都得面對同一道關卡:登入畫面。它看似簡單,卻同時牽涉到輸入欄位的型別設定、按鈕事件綁定、錯誤訊息回饋,以及最容易被忽略的一環——防止暴力