android項目之連接數據庫(eclipse(java)+soap協議+webservice服務(c#)+sql server數據庫)


 

Android客戶端開發

3.1  服務器開發

服務器的主要功能是為客戶端提供服務,客戶端發送服務請求給服務器,服務器完成客戶端的請求,然后把結果返回給客戶端,因此,構建服務器的主體是構建能夠滿足各種服務請求的功能函數,以下列出了客戶端將會用到一些函數:

☞搜索函數: public string searchButton(string keyword)

☞用戶注冊函數: public string UserRegister(string type, string androidId, string username, string pwd)

☞獲得分類下的數據函數:public string GetContentByTypeTagTwo(string type, string TypeTag)

☞由標題到正文的映射:public string GetContentBytitle(string title)

☞用戶注冊函數:public string UserRegister(string type, string androidId, string username, string pwd)

☞登入日志函數: private static void VisitLog(string username, string title, string userIP ,string logType)

 

☞讀圖片文件並轉化為字符串:

                       

string imagepath = AppDomain.CurrentDomain.BaseDirectory + @"\images\" + "localFile1.jpg";

                        FileStream fs = new FileStream(imagepath, FileMode.Open);//打開本地后保存

                        byte[] byData = new byte[fs.Length];

                        fs.Read(byData, 0, byData.Length);//現在二進制圖片在bydata數組當中

                        fs.Close();

                        //有byte轉化為string類型放在strResult當中

                        for (int i = 0; i < byData.Length; i++)

                        {

                            if (i == 0)

                                strResult += byData[i].ToString();

                            else

                                strResult += "." + byData[i].ToString();

                        }

 

運行服務器后web頁面如下所示:

                 

     

3.2         用戶客戶端開發

用戶客戶端的主要工作是設計友好的交互界面。以下介紹客戶端的主要功能:

 

任務欄分為五大類,分別是首頁、熱門、分類、搜索和菜單,首頁、熱門和分類都是文章列表,首頁顯示的是最新的咨詢,熱門顯示的是一定時期內瀏覽量最高的文章,搜索功能可以全站搜索滿足關鍵字的文章,分類分為四大類,分別是日常生活、全球新聞、學習天地合工作招聘,其文章列表按時間排序顯示全部文章。以下是所搜界面:

 

 

菜單功能分為更新、注冊、登錄和退出,如下所示:

 

更新功能能夠獲取當前最新的咨詢,點擊更新以后,會同時更新首頁、熱門和分類下的列表文章,然后跳轉到首頁。

注冊功能能夠為用戶提供注冊,注冊頁面如下所示:

 

 

客戶端界面的主要功能大體就這些。

3.3         服務器和客戶端聯合

服務器和用戶客戶端都完成以后,就要實現兩者的聯合,也就是客戶端從服務器獲取數據。客戶端從服務器獲取的過程如下:

①    客戶端向服務器發送服務請求;

②    服務器接收客戶端的請求,然后調用相關的函數,獲得數據結果;

③    服務器端將數據結果處理成JSON串,然后發送給客戶端;

④    客戶端接收服務器的發送來的JSON串,然后保存在本地緩存中;

⑤    客戶端解析JSON串,顯示數據。

服務器構建JSON串代碼如下:

  string json = "";

            json = "{\"type\":[{\"CrawlTitle\":\"CrawlTitle\",\"CrawlContent\":\"CrawlContent\",\"CreateTime\":\"CreateTime\",\"FirstImgUrl\":\"FirstImgUrl\"}";

            string jtemp = string.Empty;

            string one = string.Empty;

            string two = string.Empty;

            string third = string.Empty;

            string four = string.Empty;

            foreach (DataRow dataRow in dataTable.Rows)

            {

                jtemp = "\"CrawlTitle\":\"{0}\",\"CrawlContent\":\"{1}\",\"CreateTime\":\"{2}\",\"FirstImgUrl\":\"{3}\"";

                //獲得該圖片   網址為third = dataRow.ItemArray[3].ToString();

               

                string strResult = string.Empty;

                if (dataRow.ItemArray[3] != null && dataRow.ItemArray[3].ToString() != string.Empty && dataRow.ItemArray[3].ToString() != "")

                {

                    int localVariable=Download(dataRow.ItemArray[3].ToString(), AppDomain.CurrentDomain.BaseDirectory + @"\images\" + "localFile.jpg");//存到本地

                    if (localVariable == 1)

                    {

                        //對圖片進行壓縮

                        System.Drawing.Imaging.Encoder encoder = System.Drawing.Imaging.Encoder.Quality;//獲取品質(壓縮率)編碼

                        EncoderParameter mycoder = new EncoderParameter(encoder, 10L);//0壓縮率最大,100品質最高

                        EncoderParameters myCoders = new EncoderParameters(1);//參數數組,大小為1

                        myCoders.Param[0] = mycoder;//添加一個參數

                        ImageCodecInfo jpgInfo = GetEncoder(ImageFormat.Jpeg);//獲取JPG格式編解碼信息

                        Image bmp = Image.FromFile(AppDomain.CurrentDomain.BaseDirectory + @"\images\" + "localFile.jpg");

                        bmp.Save(AppDomain.CurrentDomain.BaseDirectory + @"\images\" + "localFile1.jpg", jpgInfo, myCoders);//以指定品質率的JPG格式保存

                        bmp.Dispose();

                        //再次讀取

                        string imagepath = AppDomain.CurrentDomain.BaseDirectory + @"\images\" + "localFile1.jpg";

                        FileStream fs = new FileStream(imagepath, FileMode.Open);//打開本地后保存

                        byte[] byData = new byte[fs.Length];

                        fs.Read(byData, 0, byData.Length);//現在二進制圖片在bydata數組當中

                        fs.Close();

                        //有byte轉化為string類型   放在  strResult當中

                        for (int i = 0; i < byData.Length; i++)

                        {

                            if (i == 0)

                                strResult += byData[i].ToString();

                            else

                                strResult += "." + byData[i].ToString();

                        }

                    }

                    else

                    {

                        strResult = "0";

                    }

                }

                else

                {

                    strResult = "0";

                }

                //轉化成json串

                one = dataRow.ItemArray[0].ToString();

                two = dataRow.ItemArray[1].ToString();

                two = two.Replace("\"", "`");

                third = dataRow.ItemArray[2].ToString();

                jtemp = string.Format(jtemp, one, two, third,strResult);//暫時直接使用圖片的地址發過去

                json += ",{" + jtemp + "}";

            }

            json += "]}";

            return json;

 

  客戶端調用服務器函數如下:

if (!file2.exists()) {
                file2.createNewFile();
            }
            FileInputStream inputStream = openFileInput(two);
            //
            // 判斷本地文件是否為空, 滿足條件就條用webservice,否則取本地數據
            //
            if (inputStream.available() == 0)// 網絡傳則flag=0
            {
                result2 = Getwebserver.GetContentById1(third, four);
                OutputStream outStream_secd = this.getBaseContext()
                        .openFileOutput(two, Context.MODE_PRIVATE);
                content = result2.toString();// 取得的webservice數據
                fileservice.save(outStream_secd, content);
            } else {// 本地傳則flag=1
                content = fileservice.read(inputStream);
                Toast.makeText(getApplicationContext(), "提示文件讀取成功",
                        Toast.LENGTH_LONG).show();
            }

上面調用的 Getwebserver.GetContentById1(third, four);//函數原型如下

    private static final String NAMESPACE = "http://wswap.daxuequn.com/";
    private static String URL = "http://wswap.daxuequn.com/Service1.asmx";

    // 由類1.1. 獲得9條相關的記錄 獲取列表
    private static final String METHO = "GetContentByTypeTagTwo";
    private static String ACTION5 = "http://wswap.daxuequn.com/GetContentByTypeTagTwo";
  
    public static String GetContentById1(String type, String TypeTag)
            throws IOException, XmlPullParserException {
        SoapPrimitive detail = null;
        try {
            String str = null;
            SoapObject rpc = new SoapObject(NAMESPACE, METHO);
//關聯到NAMESPACE, METHO  進而調用服務器上面GetContentByTypeTagTwo函數進而獲得json串
rpc.addProperty("type", type);
rpc.addProperty("TypeTag", TypeTag); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11); envelope.bodyOut = rpc; envelope.dotNet = true; envelope.setOutputSoapObject(rpc); envelope.encodingStyle = "UTF-8"; HttpTransportSE ht = new HttpTransportSE(URL); ht.debug = true; ht.call(ACTION5, envelope); detail = (SoapPrimitive) envelope.getResponse(); if (detail != null) str = detail.toString(); return str; } catch (Exception e) { e.printStackTrace(); } return ""; }

 

 客戶端解析JSON串的代碼如下:

  

JSONObject jsonResponse;

       try {

           jsonResponse = new JSONObject(jsonStr);

           // 轉換成jsonobject對象

           JSONArray jsonArray = jsonResponse.getJSONArray("type");// 獲取type屬性的value

                                                            // 為一個數組

           String title = null;

           String info = null;

           for (int i = 1; i < jsonArray.length(); i++) {

              title = jsonArray.getJSONObject(i).getString("CrawlTitle");

              // info=jsonArray.getJSONObject(i).getString("CrawlContent");

              Map<String, Object> map = new HashMap<String, Object>();

              map.put("title", title);

 

              String inputstream = jsonArray.getJSONObject(i).getString(

                     "FirstImgUrl");// 解析出圖片流 字符串

              String dtr = null;

              if (inputstream.equals("0") || inputstream.equals("")) {

                  map.put("img", R.drawable.up);

              } else {

                  String[] byte_stream = inputstream.split("\\.");

                  int num = byte_stream.length;

                  byte[] bs = new byte[num];

                  for (int j = 0; j < num; j++) {

                     int a = Integer.parseInt(byte_stream[j]);

                     char c = (char) a;

                     byte bbb = (byte) c;

                     bs[j] = bbb;

                  }

                  /* 解析好的bitmap */

                  Bitmap newbm = ImageDispose.zoomBitmap(

                         ImageDispose.BytestoBitmap(bs), 72, 72);

                  map.put("img", newbm);

              }

              list.add(map);

           }

       } catch (JSONException e) {

           // TODO Auto-generated catch block

           e.printStackTrace();

       } catch (Exception e) {

           // TODO Auto-generated catch block

           e.printStackTrace();

       }

       return list;

 

 

文件的緩存實現機制保證無網絡仍然可以看新聞,緩存的函數如下:

 

if (inputStream.available() == 0)//網絡傳則flag=0

 {           

 result2 =Getwebserver.GetContentById1(third,four);

 OutputStream outStream_secd = this.getBaseContext().openFileOutput(two, Context.MODE_PRIVATE);

 content = result2.toString();//取得的webservice數據 

 fileservice.save(outStream_secd, content);  

 }    

 else {//本地傳則flag=1

 content = fileservice.read(inputStream);

 Toast.makeText(getApplicationContext(), "提示文件讀取成功", Toast.LENGTH_LONG).show();      

 flag =1; }  

 

獲取字符串並轉化為圖片:

String[] byte_stream = inputstream.split("\\.");

 int num = byte_stream.length;

 byte[] bs = new byte[num];

 for(int j = 0 ;j < num ; j++)

 {

      int a =Integer.parseInt(byte_stream[j]);

      char c = (char)a;

      byte bbb = (byte) c;

      bs[j] = bbb;                 

 }

 Bitmap newbm = ImageDispose.zoomBitmap(ImageDispose.BytestoBitmap(bs) ,72,72);

 

 

解析成功后,獲得的文章列表和文章內容如下所示:

    

 

使用關鍵字“蘋果”搜索后界面如下:

 

 

注冊賬戶,登陸后界面如下:

具體文件見百度網盤的“創新”文件夾

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM