java Android -- 如何通过应用程序访问 ASP.NET 数据库中的数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3311681/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android -- How to access data in an ASP.NET database via app?
提问by RyanM
I have a Windows web serveralready set up with a website (unlimited application pools) and I want to be able to access a databaseon that server via the Android appI'm developing. How can I do this? Can someone point me to a tutorial or give code example of how this cross-platform (Android/Javato ASP.NET/C#) communication can be done?
我Windows web server已经建立了一个网站 ( unlimited application pools),我希望能够database通过Android app我正在开发的网站访问该服务器上的。我怎样才能做到这一点?有人可以给我指点教程或提供代码示例来说明如何完成这种跨平台 ( Android/Javato ASP.NET/C#) 通信吗?
(I'm trying to create a leader board or global scoreboard for my Androidgame on my server.)
(我正在尝试Android在我的服务器上为我的游戏创建排行榜或全球记分牌。)
Thanks.
谢谢。
回答by Jürgen Steinblock
Your app should expose a webservice. There is no native support for .net soap based webservices. But you can use the ksoap android port:
您的应用程序应该公开一个网络服务。没有对基于 .net 肥皂的网络服务的本机支持。但是你可以使用 ksoap android 端口:
http://code.google.com/p/ksoap2-android/
http://code.google.com/p/ksoap2-android/
which allows an android app to consume a .net asmx webservice. However the deserialisation of complex on the client side involves lot of code writing for every object you want so pass to the client.
它允许 android 应用程序使用 .net asmx 网络服务。然而,客户端的复杂反序列化涉及为您想要传递给客户端的每个对象编写大量代码。
I tried it for a project and there were some problems I ran into (either I could get result back to the client but the parameters i passed where always null or the other way - I could pass arguments but the result was null).
我在一个项目中尝试了它,但遇到了一些问题(或者我可以将结果返回给客户端,但我传递的参数总是为 null 或其他方式 - 我可以传递参数但结果为 null)。
Here is an example I posted for getting an int: How to call a .NET Webservice from Android using KSOAP2?
这是我发布的一个获取 int 的示例:How to call a .NET Webservice from Android using KSOAP2?
However, from my current knowlege I would suggest using a .asmx webservice that returns a json string and use a java json serialiser to parse the output. The advantages:
但是,根据我目前的知识,我建议使用返回 json 字符串的 .asmx 网络服务并使用 java json 序列化器来解析输出。优点:
- Write less code
- Faster, since mobile devices don't always have good internet connections and the xml overhead from soap is bigger than json.
- 少写代码
- 更快,因为移动设备并不总是有良好的互联网连接,并且来自 soap 的 xml 开销大于 json。
Quickstart:
快速开始:
- Create a new asmx Webservice in your .net webapp.
- Include a reference to System.Web.
Decorate your webservice class with [ScriptService] and your method with [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[ScriptService] public class WebService1 : System.Web.Services.WebService { [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public string HelloAndroid() { return "Hello Android"; } }
- 在您的 .net web 应用程序中创建一个新的 asmx Web 服务。
- 包括对 System.Web 的引用。
用 [ScriptService] 装饰你的 webservice 类,用 [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 装饰你的方法
[ScriptService] public class WebService1 : System.Web.Services.WebService { [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public string HelloAndroid() { return "Hello Android"; } }
(I think you have to add a reference to System.Web.Extension.dll which is available since .net 3.5).
(我认为您必须添加对 System.Web.Extension.dll 的引用,该引用自 .net 3.5 起可用)。
Your webservice will still return XML (so you can use it with a soap client) unless you make a HTTPPost request with content-type "application/json".
use this code to contact the webservice from 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; }if your webservice methods looks like this:
[WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public User GetUser(string name, int age) { return new User { Name = name, Age = age; } }You can call it this way from 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()); } }
除非您使用内容类型为“application/json”的 HTTPPost 请求,否则您的 Web 服务仍将返回 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()); } }
Handling server exceptions on the client side:
在客户端处理服务器异常:
Add this class to your project:
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()); } }
将此类添加到您的项目中:
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()); } }
Now replace the return statement from the sendJSONRequest with:
现在将 sendJSONRequest 中的 return 语句替换为:
JSONObject json = result != null ? new JSONObject(result) : null
if (JSONExceptionHelper.isException(json))
JSONExceptionHelper.ThrowJsonException(json);
return json;
Please note: The exception is passed to the client only if connection comes from localhost. Otherwise you get an http error 500 (or 501? I can't remember). You have to configure your IIS to send error 500 to the client.
请注意:只有当连接来自本地主机时,异常才会传递给客户端。否则,您会收到 http 错误 500(或 501?我不记得了)。您必须将 IIS 配置为向客户端发送错误 500。
Try it out and create a webservice that always throws an exception.
尝试一下并创建一个总是抛出异常的网络服务。
回答by Vincent Ramdhanie
Sounds like a job for Web Services.
听起来像是Web Services的工作。
Start by creating a Web Service on the Windows web server, you can do this with ASP.NET(or maybe this might be more current).
首先在 Windows Web 服务器上创建一个 Web 服务,您可以使用ASP.NET(或者这可能是最新的)来做到这一点。
On the Java side you can call the webservice and use the results that you get back. I think this questionmay help you get started on this side.
在 Java 端,您可以调用 Web 服务并使用返回的结果。我认为这个问题可以帮助您开始这一方面。
回答by DFDF
In case you have trouble writing web methods which return array of objects, you may want to refer here:
如果您在编写返回对象数组的 Web 方法时遇到问题,您可能需要参考这里:
ksoap android web-service tutorial
Hope it helps.
希望能帮助到你。

