輸入http://localhost/Website/WebService.asmx
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; using System.Data; using System.Data.SqlClient; ////// WebService 的摘要描述 /// [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] // 若要允許使用 ASP.NET AJAX 從指令碼呼叫此 Web 服務,請取消註解下一行。 // [System.Web.Script.Services.ScriptService] public class WebService : System.Web.Services.WebService { private const string CONNECT = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True;User Instance=True"; public WebService () { //如果使用設計的元件,請取消註解下行程式碼 //InitializeComponent(); } [WebMethod] public string HelloWorld() { return "Hello World"; } [WebMethod] public string HelloAndroid(string whoName) { string output; output = whoName + " 您好,這是Android Web Service"; return output; } [WebMethod] public string[] getMessage() { String[] output = null; output = new String[] { "早安", "Hello", "How are you?", "Ok", "7 見"}; return output; } [WebMethod] //取得資料紀錄 public string[] getRecord() { String[] output = null; //產生資料庫連線 SqlConnection conn = new SqlConnection(CONNECT); conn.Open(); //需要執行 SQL 指令 string sql = "Select msg_content, msg_now From Message Order by msg_id desc"; //產生指令物件 SqlCommand sqlcmd = new SqlCommand(sql, conn); SqlDataAdapter da = new SqlDataAdapter(); DataTable dt = new DataTable(); da.SelectCommand = sqlcmd; da.Fill(dt); //記錄筆數判斷 if (dt.Rows.Count > 0) { output = new String[dt.Rows.Count]; for (int i = 0; i < dt.Rows.Count; i++) { //讀取 msg_content output[i] = dt.Rows[i].ItemArray[0].ToString() + " "; //讀取 msg_now output[i] += dt.Rows[i].ItemArray[1].ToString(); } } da.Dispose(); dt.Dispose(); sqlcmd.Dispose(); conn.Close(); conn.Dispose(); return output; } [WebMethod] //進行資料存入動作 public int Insert(String msg_content) { SqlConnection conn = new SqlConnection(CONNECT); conn.Open(); SqlTransaction tran = conn.BeginTransaction(); string sql = "Insert into Message(msg_content,msg_now) values (@msg_content, @msg_now)"; SqlCommand sqlcmd = new SqlCommand(sql, conn, tran); sqlcmd.Parameters.Add("@msg_content", SqlDbType.Text).Value = msg_content; sqlcmd.Parameters.Add("@msg_now", SqlDbType.DateTime).Value = DateTime.Now; try { sqlcmd.ExecuteNonQuery(); tran.Commit(); } catch (Exception e) { tran.Rollback(); } sqlcmd.Dispose(); conn.Close(); conn.Dispose(); return 1; //回傳成功,呈現數字1 } }
畫面執行步驟 程式範例
package tw.edu.nfu;
import java.util.ArrayList;
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.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class TestActivity extends Activity {
    /** Called when the activity is first created. */
 private EditText input;
 private TextView output;
 private Button btn,insert;
 private ListView dataList;
 private static Handler handler;
 private static Runnable right,right_message;
 private static Runnable error,error_message;
 private static String result;
 private static String[] Msg = new String[]{"大家好","Hello","中午一起吃個飯如何","Ok", "7 見"};
 private static ArrayList messageList;
 private static String message;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        input=(EditText)findViewById(R.id.editText);
        output=(TextView)findViewById(R.id.textView1);
        dataList = (ListView)findViewById(R.id.listView1);
        btn=(Button)findViewById(R.id.btn);
        insert=(Button)findViewById(R.id.button1);
        
        btn.setOnClickListener(new Button.OnClickListener(){
   public void onClick(View arg0) {
    // TODO Auto-generated method stub
    final ProgressDialog mydialog=new ProgressDialog(TestActivity.this);
    mydialog.setTitle("請稍後!");
    mydialog.setMessage("執行中!");
    mydialog.show();
    //output.setText("測試~~~");
    //output.setText(input.getText().toString());
    System.out.println("1");
    new Thread(){
     
     public void run(){
      int num;
      int x = 10;
      int y = 3;
      
      try{
       //num = x/y; //模擬伺服器處理結果
       //System.out.println("2:" + num);
       messageList = WebService.Welcome(input.getText().toString());
       
       sleep(3000);
       handler.post(right);
      }catch(Exception a){
       System.out.println("3");
       handler.post(error);
       a.printStackTrace();
      }finally{
       System.out.println("4");
       mydialog.dismiss();
      }
     }
    }.start();
   
    handler = new Handler();
    right = new Runnable() 
    {
     public void run() {
      // TODO Auto-generated method stub
      System.out.println("6");
      output.setText(result);
      
      ArrayAdapter myAdp = new ArrayAdapter(TestActivity.this,android.R.layout.simple_list_item_1,messageList);
      dataList.setAdapter(myAdp);
     }
     
    };
    
    error = new Runnable() 
    {
     public void run() {
      // TODO Auto-generated method stub
      System.out.println("7");
      output.setText("執行失敗");
     }
     
    };
    
    System.out.println("5");
    
   }
         
        });
        
        insert.setOnClickListener(new Button.OnClickListener(){
   public void onClick(View arg0) {
    // TODO Auto-generated method stub
    final ProgressDialog mydialog=new ProgressDialog(TestActivity.this);
    mydialog.setTitle("請稍後!");
    mydialog.setMessage("紀錄新增中...!");
    mydialog.show();
    //output.setText("測試~~~");
    //output.setText(input.getText().toString());
    System.out.println("1");
    new Thread(){
     
     public void run(){
      int num;
      int x = 10;
      int y = 3;
      
      try{
       //num = x/y; //模擬伺服器處理結果
       //System.out.println("2:" + num);
       message = WebService.InsertMsg(input.getText().toString());
       
       sleep(3000);
       handler.post(right_message);
      }catch(Exception a){
       System.out.println("3");
       handler.post(error_message);
       a.printStackTrace();
      }finally{
       System.out.println("4");
       mydialog.dismiss();
      }
     }
    }.start();
   
    handler = new Handler();
    right_message = new Runnable() 
    {
     public void run() {
      // TODO Auto-generated method stub
      Toast.makeText(TestActivity.this, message, Toast.LENGTH_LONG).show();
     }
     
    };
    
    error_message = new Runnable() 
    {
     public void run() {
      // TODO Auto-generated method stub
      
     }
     
    };
    
    System.out.println("5");
    
   }
         
        });
    }
    
    public static class WebService {
     public static final String NAMESPACE = "http://tempuri.org/"; 
     public static final String URL_PATH = "http://10.0.2.2/website/";
     public static final String SERVICE_NAME = "WebService.asmx"; 
     
        public static String InsertMsg(String personal){
      
      //String method = "getMessage";
      String method = "Insert";
      String output = "";
      ArrayList list = null;
      try
      {
       
       SoapObject request = new SoapObject(NAMESPACE, method);
       request.addProperty("msg_content", personal);
       
             SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
             envelope.dotNet = true;
             envelope.setOutputSoapObject(request);  
             HttpTransportSE androidHttpTransport = new HttpTransportSE(URL_PATH + SERVICE_NAME); 
             androidHttpTransport.call(NAMESPACE + method, envelope);
             Object result = envelope.getResponse();
             output = result.toString();
             
      }catch(Exception e){}
      
      System.gc();
   
      return output;  
     }
     
     public static ArrayList Welcome(String personal){
      
      //String method = "getMessage";
      String method = "getRecord";
      String output = "";
      ArrayList list = null;
      try
      {
       
       SoapObject request = new SoapObject(NAMESPACE, method);
       //request.addProperty("whoName", personal);
       
             SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
             envelope.dotNet = true;
             envelope.setOutputSoapObject(request);  
             HttpTransportSE androidHttpTransport = new HttpTransportSE(URL_PATH + SERVICE_NAME); 
             androidHttpTransport.call(NAMESPACE + method, envelope);
             //Object result = envelope.getResponse();
             SoapObject result = (SoapObject)((SoapObject)envelope.bodyIn).getProperty(0);
             
             if(result != null && result.getPropertyCount()>0)
             {
              list  = new ArrayList();
              
              for(int i = 0; i < result.getPropertyCount(); i++)
              {
               SoapPrimitive msg_content = (SoapPrimitive)result.getProperty(i);
               list.add(msg_content.toString());
              }
             }
             
      }catch(Exception e){}
      
      System.gc();
   
      return list;  
     }
    }
}
       


 
Hi,可以請您給我這個測試檔案嗎???
回覆刪除我照著做都會失敗耶。
v03071106@gmail.com
你好~
回覆刪除這是上課練習的紀錄。
當下沒有copy檔案,請見諒