Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

WCF 與 Android 協作實戰:圖片連同參數一起上傳的完整方案

編輯: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 方式接收:

  1. using System.ServiceModel; 
  2. using System.Runtime.Serialization; 
  3. using System.ServiceModel.Web; 
  4. import System.IO; 
  5.  
  6. namespace Coreius.CEIMS.AndroidInterface 
  7. { 
  8.     [ServiceContract] 
  9.     public interface IAndroidInfo 
  10.     { 
  11.          [WebInvoke(UriTemplate = "GpsUpFile", Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, 
  12. ResponseFormat = WebMessageFormat.Json)] 
  13.         bool GpsUpFile(Stream ImageContext); 
  14.     } 
  15. }

2. 依契約實作服務內容:接收一個流的參數,先把這個 Stream 轉成位元組,再依先前約定取出第一個位元組的值,據此界定另外三個參數的位元組長度,接著透過 JSON 轉換把三個參數值取出,剩下的位元組便是手機拍的照片,將它存進伺服器 D 槽的資料夾。

  1. using System.Linq; 
  2. using System.Text; 
  3. using System.ServiceModel; 
  4. import System.ServiceModel.Web; 
  5. import System.IO; 
  6. import Newtonsoft.Json; 
  7.  
  8. namespace Coreius.CEIMS.AndroidService 
  9. { 
  10.     public class AndroidInfoService:IAndroidInfo 
  11.     { 
  12.  
  13.       public bool GpsUpFile(Stream ImageContext) 
  14.         { 
  15.             byte[] m_Bytes = ReadToEnd(ImageContext); 
  16.             int len = (int)m_Bytes[0]; 
  17.  
  18.             byte[] data = m_Bytes.Skip(1).Take(len).ToArray(); 
  19.             string Jsonstr = System.Text.Encoding.Default.GetString(data); 
  20.  
  21.             JsonModel item = JsonConvert.DeserializeObject<JsonModel>(Jsonstr); 
  22.             string ImageType=item.type; 
  23.             string EmployeeID=item.EmployeeID; 
  24.             string TaskID=item.TaskID; 
  25.  
  26.             byte[] Imagedata = m_Bytes.Skip(1 + len).ToArray(); 
  27.  
  28.             string DiskName = "d:"; 
  29.             string FileAddress = "\\UpLoad\\"; 
  30.             string LocationAddress = DiskName + FileAddress; 
  31.             if (!DirFileHelper.IsExistDirectory(LocationAddress)) 
  32.             { 
  33.                 DirFileHelper.CreateDirectory(LocationAddress); 
  34.             } 
  35.  
  36.             string ImageName = DateTime.Now.ToString("yyyyMMddhhmmss.") + ImageType; 
  37.             string ImagePath = LocationAddress + ImageName; 
  38.             if (!File.Exists(ImagePath)) 
  39.             { 
  40.                 try 
  41.                 { 
  42.                    System.IO.File.WriteAllBytes(ImagePath, Imagedata); 
  43.                     ImageContext.Close(); 
  44.                     return true; 
  45.                 } 
  46.                 catch 
  47.                 { 
  48.                    return false; 
  49.                } 
  50.             } 
  51.             else 
  52.             { 
  53.                 return false; 
  54.             } 
  55.         }  
  56.     }  
  57. }

上面的程式碼用到幾個方法,例如把流轉成位元組、把 JSON 轉成物件等,程式碼如下:

  1. public byte[] ReadToEnd(System.IO.Stream stream) 
  2.         { 
  3.             long originalPosition = 0; 
  4.  
  5.             if (stream.CanSeek) 
  6.             { 
  7.                 originalPosition = stream.Position; 
  8.                 stream.Position = 0; 
  9.             } 
  10.  
  11.             try 
  12.             { 
  13.                 byte[] readBuffer = new byte[4096]; 
  14.  
  15.                 int totalBytesRead = 0; 
  16.                 int bytesRead; 
  17.  
  18.                 while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0) 
  19.                 { 
  20.                     totalBytesRead += bytesRead; 
  21.  
  22.                     if (totalBytesRead == readBuffer.Length) 
  23.                     { 
  24.                         int nextByte = stream.ReadByte(); 
  25.                         if (nextByte != -1) 
  26.                         { 
  27.                             byte[] temp = new byte[readBuffer.Length * 2]; 
  28.                             Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length); 
  29.                             Buffer.SetByte(temp, totalBytesRead, (byte)nextByte); 
  30.                             readBuffer = temp; 
  31.                             totalBytesRead++; 
  32.                         } 
  33.                     } 
  34.  
  35.                 } 
  36.  
  37.                 byte[] buffer = readBuffer; 
  38.                 if (readBuffer.Length != totalBytesRead) 
  39.                 { 
  40.                     buffer = new byte[totalBytesRead]; 
  41.                    Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead); 
  42.                 } 
  43.                 return buffer; 
  44.             } 
  45.             finally 
  46.             { 
  47.                 if (stream.CanSeek) 
  48.                 { 
  49.                    stream.Position = originalPosition; 
  50.                 } 
  51.             } 
  52.         }  
  53.  
  54.  
  55.  
  56.     public class JsonModel 
  57.     { 
  58.         public string type { get; set; } 
  59.         public string EmployeeID { get; set; } 
  60.         public string TaskID { get; set; } 
  61.     }

3. 新建一個文字檔,把副檔名改成 .svc 作為服務發佈端(宿主為 IIS)供 Android 手機呼叫,並寫入以下內容:

  1. <%@ ServiceHost Language="C#" Debug="true" Service="Coreius.CEIMS.AndroidService.AndroidInfoService" %> 

接著修改 Web.config 的內容:

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <configuration> 
  3.   <appSettings> 
  4.     <add key="ConnectionString" value="server=127.0.0.1;database=Coreius;uid=sa;pwd=admin"/> 
  5.   </appSettings> 
  6.   <system.web> 
  7.     <compilation debug="true" targetFramework="4.0" /> 
  8.   </system.web> 
  9.   <system.serviceModel> 
  10.     <behaviors> 
  11.       <endpointBehaviors> 
  12.         <behavior name="webHttp"> 
  13.           <webHttp helpEnabled="true"/> 
  14.         </behavior> 
  15.       </endpointBehaviors> 
  16.       <serviceBehaviors> 
  17.         <behavior name="MapConfigBehavior"> 
  18.           <!-- 為避免洩漏元數據信息,請在部署前將以下值設置為 false 並刪除上面的元數據終結點 --> 
  19.           <serviceMetadata httpGetEnabled="true"/> 
  20.           <!-- 要接收故障異常詳細信息以進行調試,請將以下值設置為 true。在部署前設置為 false 以避免洩漏異常信息 --> 
  21.           <serviceDebug includeExceptionDetailInFaults="true"/> 
  22.           <dataContractSerializer maxItemsInObjectGraph="2147483647"/> 
  23.         </behavior> 
  24.       </serviceBehaviors> 
  25.     </behaviors> 
  26.  
  27.     <bindings> 
  28.       <webHttpBinding> 
  29.         <binding name="webHttpBindConfig" receiveTimeout="00:30:00" sendTimeout="00:30:00" maxReceivedMessageSize="104857600" transferMode="Streamed"> 
  30.           <readerQuotas maxStringContentLength="2147483647" maxArrayLength="2147483647"/> 
  31.           <security mode="None"></security> 
  32.         </binding> 
  33.       </webHttpBinding> 
  34.     </bindings> 
  35.     <services> 
  36.       <service name="Coreius.CEIMS.AndroidService.AndroidInfoService" behaviorConfiguration="MapConfigBehavior"> 
  37.         <endpoint binding="webHttpBinding" contract="Coreius.CEIMS.AndroidInterface.IAndroidInfo" bindingConfiguration="webHttpBindConfig" 
  38.  
  39. behaviorConfiguration="webHttp"/> 
  40.       </service> 
  41.     </services> 
  42.   </system.serviceModel> 
  43. </configuration>

此處有幾點要特別注意:

(1)此處採用的是 webHttpBinding,因此一定要設定 behaviorConfiguration 才會生效,其中 helpEnabled="true" 是為了能在發佈後查看說明資訊:

  1. <behavior name="webHttp"> 
  2.   <webHttp helpEnabled="true"/> 
  3. </behavior>

(2)為實現大檔上傳,需如下設定最大值,其中 security 是設定訪問服務的認證(此處設為不認證),transferMode 則是設定採用流的模式:

  1. <webHttpBinding> 
  2.         <binding name="webHttpBindConfig" receiveTimeout="00:30:00" sendTimeout="00:30:00" maxReceivedMessageSize="104857600" transferMode="Streamed"> 
  3.           <readerQuotas maxStringContentLength="2147483647" maxArrayLength="2147483647"/> 
  4.           <security mode="None"></security> 
  5.         </binding> 
  6.       </webHttpBinding>

完成上述程式碼後,就能在伺服器 IIS 上部署這個 WCF 服務了。

四、Android 端程式碼

由於手機端程式碼由另一位朋友撰寫,這裡把大體程式碼貼出來,原理就是把參數與圖片寫進流(圖片先進行壓縮處理),再呼叫部署好的 WCF 服務。

程式碼一:因為伺服器並非公用,下面的 IP 我隨便改了個;

  1. private void toUploadFile(File file) throws FileNotFoundException { 
  2.         String result = null; 
  3.         requestTime= 0; 
  4.         int res = 0; 
  5.         long requestTime = System.currentTimeMillis(); 
  6.         long responseTime = 0; 
  7.            
  8.         //封裝參數信息 
  9.         JSONObject jsonObject = new JSONObject(); 
  10.         try { 
  11.             jsonObject.put("EmployeeID", MainActivity.guid); 
  12.             jsonObject.put("TaskID", "e52df9b4-ee3b-46c5-8387-329b76356641"); 
  13.             String[] type = file.getName().split("\\."); 
  14.             jsonObject.put("type", type[type.length-1]); 
  15.         } catch (JSONException e) { 
  16.             // TODO Auto-generated catch block 
  17.             e.printStackTrace(); 
  18.         } 
  19.            
  20.         /**上傳文件*/ 
  21.         HttpParams httpParameters = new BasicHttpParams(); 
  22.         HttpConnectionParams.setConnectionTimeout(httpParameters, 1000*30); 
  23.         HttpConnectionParams.setSoTimeout(httpParameters, 1000*30); 
  24.         HttpConnectionParams.setTcpNoDelay(httpParameters, true); 
  25.                
  26.         String path = PictureUtil.zipNewImage(file);    //壓縮文件後返回的文件路徑 
  27.         byte[] bytes = null; 
  28.         InputStream is; 
  29.         File myfile = new File(path); 
  30.         try { 
  31.             is = new FileInputStream(path); 
  32.             bytes = new byte[(int) myfile.length()]; 
  33.             int len = 0; 
  34.             int curLen = 0; 
  35.             while ((len = is.read(bytes)) != -1) { 
  36.                 curLen += len; 
  37.                 is.read(bytes); 
  38.             } 
  39.             is.close(); 
  40.         } catch (FileNotFoundException e1) { 
  41.             // TODO Auto-generated catch block 
  42.             e1.printStackTrace(); 
  43.         } catch (IOException e) { 
  44.             // TODO Auto-generated catch block 
  45.             e.printStackTrace(); 
  46.         } 
  47.         byte[] updata = GpsImagePackage.getPacket(jsonObject.toString(), bytes);    //參數與文件封裝成單個數據包 
  48.         HttpClient httpClient = new DefaultHttpClient(httpParameters); 
  49.         HttpPost httpPost = new HttpPost(MyUrl.upload_file); 
  50.         HttpResponse httpResponse; 
  51.         //單個文件流上傳 
  52.         InputStream input = new ByteArrayInputStream( updata ); 
  53.         InputStreamEntity reqEntity; 
  54.         reqEntity = new InputStreamEntity(input, -1); 
  55.         reqEntity.setContentType("binary/octet-stream"); 
  56.         reqEntity.setChunked(true); 
  57.         httpPost.setEntity(reqEntity); 
  58.         try { 
  59.             httpResponse = httpClient.execute(httpPost); 
  60.             responseTime = System.currentTimeMillis(); 
  61.             this.requestTime = (int) ((responseTime-requestTime)/1000); 
  62.             res = httpResponse.getStatusLine().getStatusCode(); 
  63.             if (httpResponse.getStatusLine().getStatusCode() ==200) { 
  64.                 Log.e(TAG, "request success"); 
  65.                 Log.e(TAG, "result : " + result); 
  66.                 return; 
  67.             } else { 
  68.                 Log.e(TAG, "request error"); 
  69.                 sendMessage(UPLOAD_SERVER_ERROR_CODE, "上傳失敗:code=" + res); 
  70.                 return; 
  71.             } 
  72.             } catch (ClientProtocolException e) { 
  73.                // TODO Auto-generated catch block 
  74.                e.printStackTrace(); 
  75.             } catch (IOException e) { 
  76.             // TODO Auto-generated catch block 
  77.             e.printStackTrace(); 
  78.         } 
  79.     }

程式碼二:

  1. package com.anthony.util;
  2.  
  3. public class GpsImagePackage {
  4.     public GpsImagePackage() {
  5.         // TODO Auto-generated constructor stub
  6.     }
  7.  
  8.     
  9.     //封裝字節數組與參數
  10.     public static byte[] getPacket(String json,byte[] image){
  11.           
  12.         byte[] jsonb = json.getBytes();
  13.         int length = image.length + jsonb.length;
  14.         System.out.println(image.length +", "+ jsonb.length);
  15.         byte[] bytes = new byte[length+1];
  16.         byte[] lengthb = InttoByteArray(jsonb.length, 1);
  17.         System.arraycopy(lengthb, 0, bytes, 0, 1);
  18.         System.arraycopy(jsonb, 0, bytes, 1, jsonb.length);
  19.         System.arraycopy(image, 0, bytes, 1+jsonb.length, image.length);
  20.         return bytes;
  21.           
  22.     }
  23.  
  24.     
  25.     //將int轉換為字節數組
  26.     public static byte[] InttoByteArray(int iSource, int iArrayLen) {
  27.  
  28.         byte[] bLocalArr = new byte[iArrayLen];
  29.         for ( int i = 0; (i < 4) && (i < iArrayLen); i++) {
  30.             bLocalArr[i] = (byte)( iSource>>8*i & 0xFF );
  31.         }
  32.         return bLocalArr;
  33.     }
  34.  
  35.     // 將byte數組bRefArr轉為一個整數,字節數組的低位是整型的低字節位
  36.     public static int BytestoInt(byte[] bRefArr) {
  37.  
  38.         int iOutcome = 0;
  39.         byte bLoop;
  40.         for ( int i =0; i<bRefArr.length ; i++) {
  41.             bLoop = bRefArr[i];
  42.             iOutcome+= (bLoop & 0xFF) << (8 * i);
  43.         }
  44.         return iOutcome;
  45.     }
  46. }

五、運行效果:

 

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved