简体   繁体   English

通过JSON将Android应用连接到Java服务器

[英]Connecting Android app to Java server via JSON

I am creating an android app which stores data such as "name" "latitude" "longitude" in a MSSQL database. 我正在创建一个Android应用,该应用在MSSQL数据库中存储“名称”,“纬度”,“经度”等数据。

I am planning to connect the android app to a server which then connects to a mssql database server. 我打算将android应用程序连接到服务器,然后再连接到mssql数据库服务器。

I have established the Java -> MSSQL connection fine and can read/write data with no problems. 我已经建立了Java-> MSSQL连接,并且可以毫无问题地读取/写入数据。

Now I want to be able to send / receive these objects between the java server and the android app. 现在,我希望能够在Java服务器和android应用之间发送/接收这些对象。

I created 'file.json' and stored it on a web server containing: 我创建了“ file.json”并将其存储在包含以下内容的Web服务器上:

{"name":"shopname","address":"123 fake street","type":"unknown", "notes":"service is really good."}

and I am able to pull this data back into an object with no trouble. 而且我能够毫无问题地将这些数据拉回到一个对象中。

My question is: 我的问题是:

How do I get the java server to serve this data to my android app? 如何获取Java服务器以将此数据提供给我的android应用? I want to be able to use: 我希望能够使用:

URL objectGet = new URL("http://10.0.1.8/file.json");
    URLConnection yc = objectGet.openConnection();
    BufferedReader in = new BufferedReader(
            new InputStreamReader(
            yc.getInputStream()));

and then 接着

DataObject objs = gson.fromJson(in, DataObject.class);

What would be the best way of setting this up? 进行此设置的最佳方法是什么?

please refer my answer on this post. 请参考我对这篇文章的回答。 Why null value returns in json parsing in android? 为什么在android中的json解析中返回null值?

This may help you. 这可能对您有帮助。 The best way would be: 最好的方法是:

  • Connect to the server using read() function and fetch the JSON string from server 使用read()函数连接到服务器并从服务器获取JSON字符串
  • parse the read data to your object instance using GSON fromJson function 使用GSON fromJson函数将读取的数据解析为对象实例

To test your app you can host the service via IIS or Apache on your development machine and then hit your server via 要测试您的应用,您可以在开发计算机上通过IIS或Apache托管服务,然后通过

http://10.0.2.2/file.json

10.0.2.2 is the special alias to your host loopback interface (ie, 127.0.0.1 on your development machine) 10.0.2.2是主机环回接口的特殊别名(即,开发计算机上的127.0.0.1)

See: Emulator Network Address Space in the official docs 请参阅:官方文档中的仿真器网络地址空间

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM