Connecting Android app to Java server via JSON

2019-06-11 09:35发布

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?

2条回答
Emotional °昔
2楼-- · 2019-06-11 09:45

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 (i.e., 127.0.0.1 on your development machine)

See: Emulator Network Address Space in the official docs

查看更多
啃猪蹄的小仙女
3楼-- · 2019-06-11 09:54

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
查看更多
登录 后发表回答