Android客户端调用Asp.net的WebService

在Android端为了与服务器端进行通信有几种方法:1、Socket通信 2、WCF通信 3、WebService通信。因为ASP.net中发布WebService非常简单,所以我们选择用WebService来进行通信。在Android端调用.Net的WebService又有两种方法:1、开源的ksoap-2类库进行soap通信 2、通过Http请求来调用,我们选择第二种方法,简单快捷。
首先,先准备服务器端,在web.config里面的的system.Web节点添加

 <webServices>
        <protocols>
          <add name= "HttpPost"/>
          <add name= "HttpGet"/>
        </protocols>
      </webServices>

否则通过“WsUrl/方法”的路径访问WebService时会出现 “因 URL 意外地以“/方法名”结束,请求格式无法识别。执行当前 Web 请求期间生成了未处理的异常。可以使用下面的异常堆栈跟踪信息确定有关异常原因和发生位置的信息。 ”的错误。在IIS中部署网站,分配“8082”端口给该网站,然后在Windows防火墙的“高级设置”中添加“入站规则”,将“8082”端口添加访问权限到入站规则中,如果不添加入站规则,则在打开windows防火墙的情况下局域网内的客户端是不能够通过"http://192.168.1.122:8082"访问到该网站的,会显示 “无法打开网页”的错误,因此更不可能通过“http://192.168.1.122:8082/WebServices/TestService.asmx/GetUserList”访问到WebMethod。新建一个名为TestService.asmx的WebService,并在TestService.asmx中新建两个方法,一个带参数,一个不带参数,如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
//using System.Web.Script.Services;//[ScriptMethod(ResponseFormat=ResponseFormat.Json)]所需引用的命名空间
using BLL;
using Model;
namespace Test.WebServices
{
    /// <summary>
    /// TestService的摘要说明
    /// </summary>
    [WebService(Namespace = "http://www.testservice.com/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
     [System.Web.Script.Services.ScriptService]//这个属性必须把注释取消掉
    public class TestService: System.Web.Services.WebService
    {

        [WebMethod]      
        //[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
        public string HelloWorld()
        {
            return "Hello World";
        }
        [WebMethod]
       // [ScriptMethod(ResponseFormat = ResponseFormat.Json)]//不需要该属性,Android端设置Http头的Content-Type为application/json即可返回JSON数据格式给客户端
        public List<ModelUser> GetUserList()
        {
            BLLUser bllUser = new BLLUser();
            return bllUser.GetModelList();
        }
        [WebMethod]
        //[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public ModelUser GetUserByUserName(string strUserName)
        {
            BLLUser bllUser = new BLLUser();
            return bllUser.GetModel(strUserName);
        }
    }
    public class ModelUser
    {
	public string UserName{get;set;};
	public string Password{get;set;};
    }
}

ASP.net服务器端的的代码准备好之后开始编写Android客户端的代码,如下:
package com.wac.Android.TestService;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Button;

public class TestServiceActivity extends Activity {
	private static final String TAG = "TestService";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);	  
		setContentView(R.layout.main);

		OnClickListener listener = new OnClickListener() {
			public void onClick(View v) {				
				 try {  
		     //1、调用不带参数的WebMethod
                     final String SERVER_URL = "http://192.168.1.122:8082/WebServices/TestService.asmx/GetUserList"; 		  
                     HttpPost request = new HttpPost(SERVER_URL); // 根据内容来源地址创建一个Http请求  
                     request.addHeader("Content-Type", "application/json; charset=utf-8");//必须要添加该Http头才能调用WebMethod时返回JSON数据            
                     HttpResponse httpResponse = new DefaultHttpClient().execute(request); // 发送请求并获取反馈                    
                     // 解析返回的内容                      
                     if (httpResponse.getStatusLine().getStatusCode() !=404)  //StatusCode为200表示与服务端连接成功,404为连接不成功

                     {  
			     //因为GetUserList返回的是List<ModelUser>,所以该数据的JSON格式为:
			     //{"d":[{"__type":"Model.ModelUser","UserName":"wa1","Password":"123"},{"__type":"Model.ModelUser","UserName":"wa2","Password":"123"}]}
                             String result = EntityUtils.toString(httpResponse.getEntity()); 
			     Log.i("result",result);// System.out.println(result);                              
                             JSONArray resultArray=new JSONObject(result).getJSONArray("d"); //获取ModelUser类型的JSON对象数组
                             TextView tv=(TextView)findViewById(R.string.textview1);
                             tv.setText(((JSONObject)resultArray.get(0)).getString("UserName").toString()); //获取resultArray第0个元素中的“UserName”属性                           
                     }  

                     /*                    
		     //2、调用带参数的WebMethod
		     final String SERVER_URL = "http://192.168.1.122:8082/WebServices/TestService.asmx/GetUserByUserName"; // 带参数的WebMethod  
 		     HttpPost request = new HttpPost(SERVER_URL); // 根据内容来源地址创建一个Http请求  
                     request.addHeader("Content-Type", "application/json; charset=utf-8");//必须要添加该Http头才能调用WebMethod时返回JSON数据             
		     JSONObject jsonParams=new JSONObject();
                     jsonParams.put("strUserName", "wa1");//传参,如果想传递两个参数则继续添加第二个参数jsonParams.put("param2Name","param2Value")
                     HttpEntity bodyEntity =new StringEntity(jsonParams.toString(), "utf8");//参数必须也得是JSON数据格式的字符串才能传递到服务器端,否则会出现"{'Message':'strUserName是无效的JSON基元'}"的错误
                     request.setEntity(bodyEntity);
                     HttpResponse httpResponse = new DefaultHttpClient().execute(request); // 发送请求并获取反馈                    
                     // 解析返回的内容                      
                     if (httpResponse.getStatusLine().getStatusCode() !=404)  //StatusCode为200表示与服务端连接成功,404为连接不成功
                     {                  
			     //因为GetUserByUserName返回的是ModelUser,所以该数据的JSON格式为:
			     //{"d":{"__type":"Model.ModelUser","UserName":"wa1","Password":"123"}}
                             String result = EntityUtils.toString(httpResponse.getEntity()); 
			     Log.i("result",result);    
                             JSONObject resultJSON=new JSONObject(result).getJSONObject("d");//获取ModelUser类型的JSON对象                           
                             TextView tv=(TextView)findViewById(R.string.textview1);
                             tv.setText(resultJSON.getString("UserName").toString());			     
			     Log.i("resultJSON",resultJSON);                            
                     }  
		     */               
             	} catch (Exception e) {}  
	    }};
		Button button = (Button) findViewById(R.id.button1);
		button.setOnClickListener(listener);

	}
}

至此,客户端访问服务端的代码已经完成。


  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值