使用Android应用程序访问服务器上数据库的最佳方式

时间:2011-12-15 09:49:38

标签: android sql

我需要开发一个可以访问存储在办公室服务器上的SQL Server数据库的应用程序。呼叫员工远程桌面到终端服务器,并使用为其创建数据库的桌面应用程序访问数据库。桌面应用程序使用ODBC连接访问数据库。 我正在编写一个android应用程序,它将允许桌面应用程序中可用的这个数据库的一小部分访问,我正在寻找将我的应用程序连接到此数据库的方法,无论它是否使用ODBC连接(可能使用.Net),或以其他方式。

编辑:对于那些在我完成我的问题解答之前回复的人,很抱歉,它是偶然发布的,有些人在我完成编辑之前回答了。

3 个答案:

答案 0 :(得分:3)

您必须在服务器端编写Web服务。可以将数据作为Json数据包发送到设备,并在设备中解析json数据包并访问数据。您对webservice的调用应该是http调用,例如

HTTP?:\服务器\方法An Iteraitve \ get_somedata名称=东西

并且服务器应该在数据库中查询此参数并将响应发送给Json。  解析json并获取您的详细信息。

修改 在服务器响应头中将content-type设置为“application / json”。这是客户端向服务器发送http post请求的示例。这里jsonobjSend是我已经构建的json,用一些细节发送到服务器。 ex {table:“sometable”,id:90}。 jsonobjRecv是将由服务器发送的json

    HttpPost httpPostRequest = new HttpPost(url);
        StringEntity se;
        se = new StringEntity(jsonObjSend.toString());

        // Set HTTP parameters
        httpPostRequest.setEntity(se);
        httpPostRequest.setHeader("Authorization", usercredential);
        httpPostRequest.setHeader("Accept", "application/json");
        httpPostRequest.setHeader("Content-type", "application/json");
        httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set this parameter if you would like to use gzip compression
        long t = System.currentTimeMillis();
        response = (HttpResponse) httpclient.execute(httpPostRequest);
        Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis()-t) + "ms]");
        //Get hold of the response entity (-> the data):
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            // Read the content stream
            InputStream instream = entity.getContent();
            Header contentEncoding = response.getFirstHeader("Content-Encoding");
            if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
                instream = new GZIPInputStream(instream);
            }

            // convert content stream to a String
            String resultString= convertStreamToString(instream);
            Log.v(null, "resultString "+resultString);
            instream.close();


            // Transform the String into a JSONObject
            if(resultString!=null){
                jsonObjRecv = new JSONObject(resultString);

            }

            // Raw DEBUG output of our received JSON object:
            Log.i(TAG,"<jsonobject>\n"+jsonObjRecv.toString()+"\n</jsonobject>");

            return jsonObjRecv;

}

创建/解析json check json.org

答案 1 :(得分:2)

您必须创建一个将成为界面的Web服务器,然后您可以为您的应用程序提供Web服务。

如果您可以修改桌面应用程序,请直接实施http服务。 因此,只有在您的应用程序启动时才能使用该服务。

正如AnDro所说,你可以选择json,这将是数据传输的轻量级。 如果您选择json techno,请查看jackson

答案 2 :(得分:0)

还会建议一个接受JSON发布的RESTful API - 并返回JSON结果。

您还可以添加URL重写,将URL分发给各种控制器。

e.g。 http // somehost.com / controller / action ...你可以在哪里发帖。

这可以在ASP.NET中完成(最近在PHP中编写了类似的东西)。