c#如何写与andriod之间的接口

2025-10-30 02:25:04

1、由于我对C#比较熟悉,所以我优先使用自己熟悉的技术来搭建WebService的项目。很简单我们就用VS工具创建一个Web服务应用程序(VS2008,而从VS2010开始优先使用WCF来创建服务应用程序了,不过用WCF框架创建WebService也是很容易的)。

c#如何写与andriod之间的接口

2、这个WebService的方法很简单,就是组建一个DataTable的数据类型,并通过CreateJsonParameters方法转化为JSON字符串。这里面的DataTable可以修改成从数据库端读取数据到DataTable对象。

c#如何写与andriod之间的接口

3、这个方法是我从网上随便找到的一个方法,比较土了,就是直接拼接JSON字符串(无所谓,这不是我们要关心的重点)。

WebService端准备好,就可以将其发布到IIS。发布方法跟网站一样,如果是本机的话,可以直接测试WebService方法返回得到的结果,比如调用后会得到如下结果:

这里肯定有人问,这外面是XML,里面又是JSON,这不是“四不像”吗?是的,我这样做是想说明一点,WebService是基于Soap的,数据传输的格式就是XML,所以这里得到XML文档是理所当然。如果你想得到纯净的JSON字符串,可以使用C#中的WCF框架(可以指定客户端返回JSON格式)或者Java中的Servlet(直接刷出JSON文本)。

好,接下来我们要做两件事:

1、请求这个WebService得到这个JSON字符串

2、格式化这个JSON字符串在Android中显示

我们先提供一个助手类,这是我自己动手封装了一下这两个操作所需要的方法。

4、/** 

 * @author gary.gu 助手类 

 */  

public final class Util {  

    /** 

     * @param nameSpace  WS的命名空间 

     * @param methodName WS的方法名 

     * @param wsdl       WS的wsdl的完整路径名 

     * @param params     WS的方法所需要的参数 

     * @return           SoapObject对象 

     */  

    public static SoapObject callWS(String nameSpace, String methodName,  

            String wsdl, Map<String, Object> params) {  

        final String SOAP_ACTION = nameSpace + methodName;  

        SoapObject soapObject = new SoapObject(nameSpace, methodName);  

  

        if ((params != null) && (!params.isEmpty())) {  

            Iterator<Entry<String, Object>> it = params.entrySet().iterator();  

            while (it.hasNext()) {  

                Map.Entry<String, Object> e = (Map.Entry<String, Object>) it  

                        .next();  

                soapObject.addProperty(e.getKey(), e.getValue());  

            }  

        }  

  

        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(  

                SoapEnvelope.VER11);  

        envelope.bodyOut = soapObject;  

          

        // 兼容.NET开发的Web Service  

        envelope.dotNet = true;  

  

        HttpTransportSE ht = new HttpTransportSE(wsdl);  

        try {  

            ht.call(SOAP_ACTION, envelope);  

            if (envelope.getResponse() != null) {  

                SoapObject result = (SoapObject) envelope.bodyIn;  

                return result;  

            } else {  

                return null;  

            }  

        } catch (Exception e) {  

            Log.e("error", e.getMessage());  

        }  

        return null;  

    }  

  

    /** 

     *  

     * @param result JSON字符串 

     * @param name   JSON数组名称 

     * @param fields JSON字符串所包含的字段 

     * @return       返回List<Map<String,Object>>类型的列表,Map<String,Object>对应于 "id":"1"的结构 

     */  

    public static List<Map<String, Object>> convertJSON2List(String result,  

            String name, String[] fields) {  

        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();  

        try {  

            JSONArray array = new JSONObject(result).getJSONArray(name);  

  

            for (int i = 0; i < array.length(); i++) {  

                JSONObject object = (JSONObject) array.opt(i);  

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

                for (String str : fields) {  

                    map.put(str, object.get(str));  

                }  

                list.add(map);  

            }  

        } catch (JSONException e) {  

            Log.e("error", e.getMessage());  

        }  

        return list;  

    }  

}  

5、Tips:我们都知道C#中给方法加注释,可以按3次“/”,借助于VS就可以自动生成。而在Eclipse当中,可以在方法上面输入“/**”然后按下回车就可以自动生成。

6、public class TestWS extends Activity {  

  

    @Override  

    protected void onCreate(Bundle savedInstanceState) {  

        super.onCreate(savedInstanceState);  

  

        RelativeLayout l = new RelativeLayout(this);  

        Button button = new Button(l.getContext());  

        button.setText("点击本机webservice");  

        l.addView(button);  

        setContentView(l);  

  

        button.setOnClickListener(new View.OnClickListener() {  

  

            @Override  

            public void onClick(View v) {  

  

                final String nameSpace = "http://tempuri.org/";  

                final String methodName = "DataTableTest";  

                final String wsdl = "http://10.77.137.119:8888/webserviceTest/Service1.asmx?WSDL";  

  

                //调用WebService返回SoapObject对象  

                SoapObject soapObject = Util.callWS(nameSpace, methodName,  

                        wsdl, null);  

                if (soapObject != null) {  

                      

                    //获得soapObject对象的DataTableTestResult属性的值  

                    String result = soapObject.getProperty(  

                            "DataTableTestResult").toString();  

  

                    Toast.makeText(TestWS.this, result, Toast.LENGTH_SHORT)  

                            .show();  

  

                    try {  

                        //将JSON字符串转换为List的结构  

                        List<Map<String, Object>> list = Util.convertJSON2List(  

                                result, "Result_List", new String[] { "id",  

                                        "name", "email" });  

  

                        //通过Intent将List传入到新的Activity  

                        Intent newIntent = new Intent(TestWS.this,  

                                GridViewTest.class);  

                        Bundle bundle = new Bundle();  

                          

                        //List一定是一个Serializable类型  

                        bundle.putSerializable("key", (Serializable) list);  

                        newIntent.putExtras(bundle);  

                          

                        //启动新的Activity  

                        startActivity(newIntent);  

  

                    } catch (Exception e) {  

                        e.printStackTrace();  

                    }  

                } else {  

                    System.out.println("This is null...");  

                }  

            }  

        });  

    }  

  

}  

7、这里面有两点需要注意:

1、这个Activity并没有加载layout布局文件,而是通过代码创建了一个Button,这也是一种创建视图的方法。

2、通过Intent对象,我们将List<Map<String,Object>>传入到了新的Activity当中,这种Intent之间的传值方式需要注意。

public class GridViewTest extends Activity {  

  

    GridView grid;  

  

    @Override  

    protected void onCreate(Bundle savedInstanceState) {  

        super.onCreate(savedInstanceState);  

        setContentView(R.layout.activity_gridview);  

  

        Intent intent = this.getIntent();  

        Bundle bundle = intent.getExtras();  

  

        //获得传进来的List<Map<String,Object>>对象  

        @SuppressWarnings("unchecked")  

        List<Map<String, Object>> list = (List<Map<String, Object>>) bundle  

                .getSerializable("key");  

  

        //通过findViewById方法找到GridView对象  

        grid = (GridView) findViewById(R.id.grid01);  

          

        //SimpleAdapter适配器填充  

        //1.context    当前上下文,用this表示,或者GridViewTest.this  

        //2.data       A List of Maps.要求是List<Map<String,Object>>结构的列表,即数据源  

        //3.resource   布局文件  

        //4.from       从哪里来,即提取数据源List中的哪些key  

        //5.to         到哪里去,即填充布局文件中的控件  

        SimpleAdapter adapter = new SimpleAdapter(this, list,  

                R.layout.list_item, new String[] { "id", "name", "email" },  

                new int[] { R.id.id, R.id.name, R.id.email });  

          

        //将GridView和适配器绑定  

        grid.setAdapter(adapter);  

    }  

  

}  

8、先获得传过来的List对象,然后通过SimpleAdapter绑定到GridView。

activity_gridview.xml 布局文件:

<?xml version="1.0" encoding="utf-8"?>  

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  

    android:layout_width="match_parent"  

    android:layout_height="match_parent"  

    android:orientation="vertical" >  

      

    <GridView   

        android:id="@+id/grid01"  

        android:layout_width="fill_parent"  

        android:layout_height="wrap_content"  

        android:horizontalSpacing="1pt"  

        android:verticalSpacing="1pt"  

        android:numColumns="3"  

        android:gravity="center"/>  

  

</LinearLayout>  

9、list_item.xml 布局文件:

<?xml version="1.0" encoding="utf-8"?>  

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  

    android:layout_width="match_parent"  

    android:layout_height="wrap_content"  

    android:gravity="center_vertical"  

    android:orientation="vertical" >  

  

    <TextView  

        android:id="@+id/id"  

        android:layout_width="wrap_content"  

        android:layout_height="wrap_content" />  

  

    <TextView  

        android:id="@+id/name"  

        android:layout_width="wrap_content"  

        android:layout_height="wrap_content" />  

  

    <TextView  

        android:id="@+id/email"  

        android:layout_width="wrap_content"  

        android:layout_height="wrap_content" />  

  

</LinearLayout>  

10、AndroidManifest.xml完整配置:

<?xml version="1.0" encoding="utf-8"?>  

<manifest xmlns:android="http://schemas.android.com/apk/res/android"  

    package="com.example.webservicedemo"  

    android:versionCode="1"  

    android:versionName="1.0" >  

  

    <uses-sdk  

        android:minSdkVersion="8"  

        android:targetSdkVersion="14" />  

  

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

  

    <application  

        android:allowBackup="true"  

        android:icon="@drawable/ic_launcher"  

        android:label="@string/app_name"  

        android:theme="@style/AppTheme" >  

        <activity  

            android:name=".TestWS"  

            android:label="@string/app_name" >  

            <intent-filter>  

                <action android:name="android.intent.action.MAIN" />  

  

                <category android:name="android.intent.category.LAUNCHER" />  

            </intent-filter>  

        </activity>  

        <activity  

            android:name=".GridViewTest"  

            android:label="@string/app_name" >  

        </activity>  

    </application>  

  

</manifest>  

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢