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

标签 c# java asp.net android http

我有一个 Windows 网络服务器,已经设置了一个网站(无限应用程序池),我希望能够访问一个数据库 通过我正在开发的 Android 应用程序 在该服务器上。我怎样才能做到这一点?有人可以给我指点教程或代码示例来说明如何完成这种跨平台(Android/JavaASP.NET/C#)通信吗?

(我正在尝试为我的服务器上的 Android 游戏创建排行榜或全局记分牌。)

谢谢。

最佳答案

您的应用应该公开网络服务。 没有对基于 .net soap 的 web 服务的 native 支持。但是您可以使用 ksoap android 端口:

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

它允许 Android 应用程序使用 .net asmx 网络服务。 然而,在客户端反序列化 complex 涉及为您想要传递给客户端的每个对象编写大量代码。

我在一个项目中尝试过它,但遇到了一些问题(要么我可以将结果返回给客户端,但我传递的参数总是 null 或其他方式 - 我可以传递参数但结果为 null) .

这是我发布的用于获取 int 的示例:How to call a .NET Webservice from Android using KSOAP2?

但是,根据我目前的知识,我建议使用返回 json 字符串的 .asmx 网络服务,并使用 java json 序列化程序来解析输出。优点:

  • 少写代码
  • 更快,因为移动设备并不总是有良好的互联网连接,而且 soap 的 xml 开销比 json 大。

快速入门:

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

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

(我认为您必须添加对自 .net 3.5 以来可用的 System.Web.Extension.dll 的引用)。

  • 除非您使用内容类型“application/json”发出 HTTPPost 请求,否则您的网络服务仍将返回 XML(因此您可以将它与 soap 客户端一起使用)。

  • 使用此代码从 android 联系网络服务:

    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;
    }
    

    如果您的网络服务方法如下所示:

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

    你可以在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());
            }
    }
    

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

  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());
        }
    
    }
    

现在将 sendJSONRequest 的返回语句替换为:

    JSONObject json = result != null ? new JSONObject(result) : null
    if (JSONExceptionHelper.isException(json))
        JSONExceptionHelper.ThrowJsonException(json); 
    return json;

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

试一试并创建一个始终抛出异常的网络服务。

关于c# - Android -- 如何通过应用程序访问 ASP.NET 数据库中的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3311681/

相关文章:

java - 如何使用spinner和image传递之前的数据?

c# - 无法从 IIS 打开数据库错误

c# - 从数据集中读取数据

C# 动态类型导致 Console.WriteLine 在 IL 中通过反射解析

c# - 在图片框上绘图时位置错误

c# - 如何创建需要 4 个字符且无空格的正则表达式?

asp.net - __doPostBack 在 IE11 中未定义

c# - 如何刷新net core中的JWT?

java - 我的 getView 方法没有被调用以在 ListView 中填充数据

java - 验证输入日期