简体   繁体   中英

Consume web service providing updating JSON object

I need help with a school project, I need to connect to a web service providing a JSON document updating every 3 or 4 second, consume it and use some of the information contained. The JSON looks like this:

{ "firstName": "John",
"lastName": "Smith",
"isAlive": true,
"age": 25,
"height_cm": 167.6,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021-3100"
},
"phoneCalls": [
{
"type": "home",
"number": "212 555-1234",
"duration": "32"
},
{
"type": "office",
"number": "646 555-4567",
"duration": "79"
}
]
}

Every x second the Json file is updated with random calls added to the document, i need to use those information.

I'm not sure how to connect to this local web service, and retrieve this information from this updating document, I'd like to use JAVA but let me know if there are better solution.

Thanks for all the tips you can provide me.

See this example on how to return a JSONObject from a given url via http in Java. This includes support for basic authentication, you may or may not need it.

What you would do is call this method using a timer to refresh your feed as needed.

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Base64;

... other imports

public static JSONObject readJSONFeed(String URL, String username,
        String password) throws KeyManagementException,
        UnrecoverableKeyException, NoSuchAlgorithmException,
        KeyStoreException, ClientProtocolException, IOException {

    String auth = username + ":" + password;
    HttpClient httpClient = = new DefaultHttpClient;

    StringBuilder stringBuilder = new StringBuilder();

    // Build HTTP request
    HttpPost httpPost = new HttpPost(URL);
    httpPost.setHeader(
            "Authorization",
            "Basic "
                    + Base64.encodeToString(auth.getBytes(), Base64.NO_WRAP));
    httpPost.setHeader("Accept", "application/json");

    // send the request
    HttpResponse response = httpClient.execute(httpPost);

    // read the result
    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    if (statusCode == 200) {
        HttpEntity entity = response.getEntity();
        InputStream inputStream = entity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                inputStream));
        String line;
        while ((line = reader.readLine()) != null) {
            stringBuilder.append(line);
        }
        inputStream.close();
    } else if (statusCode == 401) {
        throw new IOException("Authentication failed");
    } else {
        throw new IOException(statusLine.getStatusCode() + ":"
                + statusLine.getReasonPhrase());
    }

    // Return the JSON Object
    return new JSONObject(stringBuilder.toString());
}

after that, you can retrieve the data by using the methods of the JSONObject class, such as getInt(String) or getString(String) . You can obtain nested objects with getJSONObject(String) . All by providing a string with the name of the field/object as parameter.

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