• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Android访问C#.NetWebservice(简单例子适合初学者)

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本人FQ找来的 暂时没有翻译 后续翻译过来、

原文地址  http://adrianandroid.blogspot.com/2012/05/access-c-net-web-service-in.html

  • 首先,将告诉你如何在Visual Studio中创建 web serviceSQL数据库)的5个步骤

Step 1            
     点击 File--->web Site(click)  --->ASP .Net web Service      

 

Step 2 : 创建一个数据库表
           如果你没有创建数据库连接,请先创建数据库连接,或这点击ctrl + alt + s 连接你的数据库,添加你的数据库
           在你数据库表中点击Add new Table创建数据库表


创建你的数据库表

输入表名称,并点击OK保存

输入一些样品数据

 

Step 3 : 在连接管理器中添加一个新的类
  

 
give a class name :- ConnectionManager.Class

 

 
click "Yes" button

 

双击你的连接管理器的class类,然后输入一下代码

//---------------------------------------- 
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;


public class ConnectionManager
{
    public static SqlConnection NewCon;
    public static string ConStr = 
"Data Source=ADRIAN-PC\\SQLEXPRESS;Initial Catalog=SimpleLife;Integrated Security=True";

    public static SqlConnection GetConnection()
    {
        NewCon = new SqlConnection(ConStr);
        return NewCon;
    }

}
//------------------------------------------------------------------------ 

       在这个代码中,要根据你的数据库连接参数修改 ConStr 参数

Step 4 : 添加一个新的web method

 

                                                                双击 Service.cs文件
双击 Service.cs -->然后输入一下代码(复制 &粘贴)

//---------------------------------------------------- 
using System;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Data;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

public class Service : System.Web.Services.WebService
{
    public Service () {

        
    }

    [WebMethod]
    public string findContact(string eid) {

       return getContact(eid);
    }


    public String getContact(String eid)
    {

        SqlConnection conn;
        conn = ConnectionManager.GetConnection();
        conn.Open();
      
        SqlCommand newCmd = conn.CreateCommand();
      
        newCmd.CommandType = CommandType.Text;
        newCmd.CommandText = "select Name from dbo.StudentContact where studentNo='" + eid + "'";
        SqlDataReader sdr = newCmd.ExecuteReader();
        String address=null;
        if (sdr.Read())
        {
            address = sdr.GetValue(0).ToString();
        }
    
        conn.Close();
        return address;
        

    }

}
//------------------------------------------------------

 



Step 5 : 启动你的web service

 
这是你的 web service界面  


现在你能看到你创建的webs service 方法显示: findContact( )

现在我们可以看看这个Web服务是正确的工作点击findContact浅蓝色的Web服务

 

  根据Value的类型在文本框中输入你的学生编号数据.

现在这个Web服务执行正常,会显示你输入的编号查询出学生姓名

  • Now I will tell you how to access this web service in Android


Step 1 : create your android project and create this main XML file

 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <EditText 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:text="Type Student no" 
    android:id="@+id/editText1">                           
    </EditText>
    
    <Button 
    android:text="Get Name" 
    android:id="@+id/button1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content">
    </Button>
    
    <TextView 
    android:text="from Web service" 
    android:id="@+id/textView1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content">
    </TextView>
    
</LinearLayout>

 

 
Step 2 : Download (http://sourceforge.net/projects/ksoap2/) KSOAP from the internet and locate on your hard disk.And add to the to your Android Project
 
download link :- 
 
 
 
 
 
Step 3 :在你的 Main Activity.Java 中输入一下代码,这里主要要注意引用ksoap2
 

package com.webservice;             //In Here Your package com."    your one     ";
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;



import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Main extends Activity 
{
    /** Called when the activity is first created. */
    private static final String SOAP_ACTION = "http://tempuri.org/findContact";
    
    private static final String OPERATION_NAME = "findContact";// your webservice web method name
    
    private static final String WSDL_TARGET_NAMESPACE = "http://tempuri.org/";
    
    private static final String SOAP_ADDRESS = "http://10.0.2.2:1506/WebSite3/Service.asmx";
 
// for the SOAP_ADDRESS, run your web service & see 
//your web service Url :1506/WebSite3/Service.asmx ,1052 will be change according to your PC

    TextView tvData1;
    EditText edata;
    Button button;
    String studentNo;
//http://localhost:1827/WebSite1/Service.asmx/HelloWorld
   
    //http://10.0.2.2:1827/WebSite1/Service.asmx
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        tvData1 = (TextView)findViewById(R.id.textView1);
       
        
        button=(Button)findViewById(R.id.button1);
        
        button.setOnClickListener(new OnClickListener() {
            
            public void onClick(View v) {
                  SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,     OPERATION_NAME);
                    PropertyInfo propertyInfo = new PropertyInfo();
                    propertyInfo.type = PropertyInfo.STRING_CLASS;
                    propertyInfo.name = "eid";
                    
                    edata =(EditText)findViewById(R.id.editText1);
                    studentNo=edata.getText().toString();
                    
                    request.addProperty(propertyInfo, studentNo);
                            
                            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                            SoapEnvelope.VER11);
                            envelope.dotNet = true;
                            
                            envelope.setOutputSoapObject(request);
                            
                            HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);
                            
                            try  {                    
                            httpTransport.call(SOAP_ACTION, envelope);                    
                            Object response = envelope.getResponse();                    
                            tvData1.setText(response.toString());                    
                            }  catch (Exception exception)   {
                                          tvData1.setText(exception.toString()+"  Or enter number is not Available!");                    
                            }
                    
                    tvData1 = (TextView)findViewById(R.id.textView1);
                
            }
        });
        
                  
        //client = new DefaultHttpClient();            
        //new Read().execute("text");
 }
}

 


Step 4 : 需要在AndroidManifest.xml中定义相应的权限(以获取internet访问权限为例),如下:
    
         
 
< uses-permission   android:name =”android.permission.INTERNET”  />  

注意在<application>也可以定义INTERNET权限,如下:

< application   android:permission =”android.permission.INTERNET” >  
" Internet User Permission "

 
Step 5 : 启动你的APP
 
 
type Student No then click the button
 
 
最后,祝你好运!
 
 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap