Android - 如何通过应用程序访问ASP.NET数据库中的数据?

Rya*_*anM 2 c# java asp.net android http

Windows web server已经设置了一个网站(unlimited application pools),我希望能够database通过Android app我正在开发的访问该服务器上的一个.我怎样才能做到这一点?有人能指点我一个教程或给出如何进行这种跨平台(Android/JavaASP.NET/C#)通信的代码示例吗?

(我正试图Android在我的服务器上为我的游戏创建一个排行榜或全球记分牌.)

谢谢.

Jür*_*ock 12

您的应用应该公开Web服务.基于.net soap的webservices没有本机支持.但你可以使用kso​​ap android端口:

http://code.google.com/p/ksoap2-android/

这允许Android应用程序使用.net asmx webservice.然而,客户端上的复杂的反序列化涉及为您想要的每个对象编写大量代码,因此传递给客户端.

我尝试了一个项目,并遇到了一些问题(或者我可以将结果返回给客户端,但我传递的参数总是为null或者另一种方式 - 我可以传递参数,但结果为null).

以下是我发布的获取int的示例:如何使用KSOAP2从Android调用.NET Web服务?

但是,从我目前的知识,我建议使用.asmx webservice返回一个json字符串并使用java json序列化程序来解析输出.优点:

  • 写更少的代码
  • 更快,因为移动设备并不总是具有良好的互联网连接,并且肥皂的xml开销大于json.

快速开始:

  • 在.net webapp中创建一个新的asmx Webservice.
  • 包括对System.Web的引用.
  • 使用[ScriptService]装饰您的web服务类,使用[ScriptMethod(ResponseFormat = ResponseFormat.Json)]装饰您的方法

    [ScriptService]
    public class WebService1 : System.Web.Services.WebService 
    {
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string HelloAndroid()
        {
            return "Hello Android";
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)

(我想你必须添加一个自.net 3.5以来可用的System.Web.Extension.dll的引用).

  • 您的Web服务仍将返回XML(因此您可以将其与soap客户端一起使用),除非您使用内容类型"application/json"发出HTTPPost请求.

  • 使用此代码联系android的web服务:

    private JSONObject sendJsonRequest(string host, int port,
           String uri, JSONObject param) 
                throws ClientProtocolException, IOException, JSONException
    {
        HttpClient httpClient = new DefaultHttpClient();
        HttpHost httpHost = new HttpHost(host, port);   
        HttpPost httpPost = new HttpPost(uri);
        httpPost.addHeader("Content-Type", "application/json; charset=utf-8");
    
        if (param != null)
        {
            HttpEntity bodyEntity = new StringEntity(param.toString(), "utf8");
            httpPost.setEntity(bodyEntity);
        }
    
        HttpResponse response = httpClient.execute(httpHost, httpPost);
        HttpEntity entity = response.getEntity();
    
        String result = null;
        if (entity != null) {
            InputStream instream = entity.getContent();
            BufferedReader reader = new BufferedReader(
                 new InputStreamReader(instream));
            StringBuilder sb = new StringBuilder();
    
            String line = null;
            while ((line = reader.readLine()) != null)
                sb.append(line + "\n");
    
            result = sb.toString();
            instream.close();           
        }
    
        httpPost.abort();
        return result != null ? new JSONObject(result) : null;
    }
    
    Run Code Online (Sandbox Code Playgroud)

    如果您的webservice方法如下所示:

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public User GetUser(string name, int age)
    {
        return new User { Name = name, Age = age; }
    }
    
    Run Code Online (Sandbox Code Playgroud)

    你可以这样从android调用它:

    public void getUser() {
        // if you put a json object to the server
        // the properties are automagically mapped to the methods' input parameters
        JSONObject param = new JSONObject();
        param.put("name", "John Doe");
        param.put("age", 47);
    
    
            JSONObject result = sendJsonRequest("server", 80, 
                  "http://server:80/service1.asmx/GetUser", param);
            if (result != null) {
                JSONObject user = new JSONObject(result.getString("d"));
                // .net webservices always return the result
                // wrapped in a parameter named "d"
                system.out.println(user.getString("name"));
                system.out.println(user.getInt("age").toString());
            }
    }
    
    Run Code Online (Sandbox Code Playgroud)

在客户端处理服务器异常:

  1. 将此类添加到项目中:

    import org.json.JSONException;
    import org.json.JSONObject;
    
    public class JSONExceptionHelper {
    
        private static final String KEY_MESSAGE = "Message";
        private static final String KEY_EXCEPTIONTYPE = "ExceptionType";
        private static final String KEY_STACKTRACE = "StackTrace";
    
        public static boolean isException(JSONObject json) {
            return json == null 
                ? false
                : json.has(KEY_MESSAGE) && 
                  json.has(KEY_EXCEPTIONTYPE) && 
                  json.has(KEY_STACKTRACE);
        }
    
        public static void ThrowJsonException(JSONObject json) throws JSONException {
    
            String message = json.getString(KEY_MESSAGE);
            String exceptiontype = json.getString(KEY_EXCEPTIONTYPE);
            String stacktrace = json.getString(KEY_STACKTRACE);
    
            StringBuilder sb = new StringBuilder();
            sb.append(exceptiontype);
            sb.append(": ");
            sb.append(message);
            sb.append(System.getProperty("line.separator"));
            sb.append(stacktrace);
    
            throw new JSONException(sb.toString());
        }
    
    }
    
    Run Code Online (Sandbox Code Playgroud)

现在用sendJSONRequest替换return语句:

    JSONObject json = result != null ? new JSONObject(result) : null
    if (JSONExceptionHelper.isException(json))
        JSONExceptionHelper.ThrowJsonException(json); 
    return json;
Run Code Online (Sandbox Code Playgroud)

请注意:仅当连接来自localhost时才会将异常传递给客户端.否则你得到一个http错误500(或501?我不记得了).您必须配置IIS以将错误500发送到客户端.

尝试一下,创建一个始终抛出异常的Web服务.