简体   繁体   中英

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.

I am planning to connect the android app to a server which then connects to a mssql database server.

I have established the Java -> MSSQL connection fine and can read/write data with no problems.

Now I want to be able to send / receive these objects between the java server and the android app.

I created 'file.json' and stored it on a web server containing:

{"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? 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?

This may help you. The best way would be:

  • Connect to the server using read() function and fetch the JSON string from server
  • parse the read data to your object instance using GSON fromJson function

To test your app you can host the service via IIS or Apache on your development machine and then hit your server via

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)

See: Emulator Network Address Space in the official docs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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