[Android] 透過WebService連接MSSQL

  • 29230
  • 0
  • 2013-03-28

程式雖然簡單, 但由於Android及ksoap2版本不同, 因此試了很久

STP1. 建立WebService, 預設Namespace, 方法名稱SNQuery, 輸入輸出皆為string

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;

namespace SNQueryWebService
{
    /// 
    ///Service1 的摘要描述
    /// 
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允許使用 ASP.NET AJAX 從指令碼呼叫此 Web 服務,請取消註解下一行。
    // [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {
        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }

        [WebMethod]
        public string SNQuery(string SN)
        {
            SqlConnection conn = new SqlConnection("server=***;database=***;uid=***;pwd=***");
            conn.Open();
            SqlCommand s_com = new SqlCommand();
            s_com.CommandText = "SELECT * FROM SerialNumber WHERE SN='" + SN + "'"; 
            s_com.Connection = conn;
            SqlDataReader s_read = s_com.ExecuteReader();
            bool result = s_read.HasRows;
            s_read.Close();
            conn.Close();
            if (result)
                return SN + " Found";
            else
                return SN + " NOT Found";
        }
    }
}

 

STP2. 部屬.asmx, .asmx.cs, bin至Server, IIS>AWS>ConvertToApplication, 加.asmx為預設畫面


STP3. 下載ksoap2, 我使用的版本是2.5.2, 複製至\libs下, 並匯入Eclipse, Project>Proerties>JavaBuildPath>Libraries>AddExternalJAR..>OK

ksoap2-android-assembly-2.5.2-jar-with-dependencies.jar.zip


STP4. File>New>AndroidApplicationProject, 編輯res/layout/activity_main.xml如下


STP5. 編輯src/../MainActivity.java如下

package com.example.CallWebService;

import org.ksoap2.SoapEnvelope; 
import org.ksoap2.serialization.SoapObject; 
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope; 
import org.ksoap2.transport.HttpTransportSE; 

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

	private static final String NAMESPACE = "http://tempuri.org/" ; 
	private static final String URL = "http://192.168.20.14/AWS/SNQuery.asmx";  
	private static final String SOAP_ACTION = "http://tempuri.org/SNQuery"; 
	private static final String METHOD_NAME = "SNQuery";
	
	private EditText SNInput;
	private TextView ResultOutput;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SNInput = (EditText) findViewById(R.id.SNEditText);
        ResultOutput = (TextView) findViewById(R.id.ResultEditText);       				
    }
    
    public void SNonClick(View snView) {
    	Thread networkThread = new Thread() {     
        	@Override    
        	public void run() {
        		try {
        			SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); 
        			request.addProperty("SN", SNInput.getText().toString());
        			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);   
        			envelope.dotNet = true;//若WS有輸入參數必須要加這一行否則WS沒反應
        			envelope.setOutputSoapObject(request);
        			HttpTransportSE ht = new HttpTransportSE(URL);          
        			ht.call(SOAP_ACTION, envelope);          
        			final SoapPrimitive response = (SoapPrimitive)envelope.getResponse();           
        			runOnUiThread (new Runnable(){       
        				public void run() {          
        					ResultOutput.setText(response.toString());            
        				}        
        			});       
        		}catch (Exception e) {          
        			e.printStackTrace();      
        		}     
        	}   
        };   
        networkThread.start();//網友說Android 3.0後網路存取必須在Thread中run
    }
        
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
}

 

STP6. 於AndroidManifest.xml編輯網路存取連線

<uses-permission android:name="android.permission.INTERNET"/>

 

STP7. 結果如下

 

REF. 原始檔

CallWebService.zip

SNQueryWebService.zip