简体   繁体   English

消费Web服务,提供更新的JSON对象

[英]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. 我需要一个学校项目的帮助,我需要连接到提供JSON文档的Web服务,该文档每3或4秒更新一次,使用它并使用其中包含的某些信息。 The JSON looks like this: JSON如下所示:

{ "firstName": "John", {“ firstName”:“ John”,
"lastName": "Smith", “ lastName”:“ Smith”,
"isAlive": true, “ isAlive”:是的,
"age": 25, “年龄”:25岁,
"height_cm": 167.6, “ height_cm”:167.6,
"address": { “地址”: {
"streetAddress": "21 2nd Street", “ streetAddress”:“ 21 2nd Street”,
"city": "New York", “ city”:“ New York”,
"state": "NY", “ state”:“ NY”,
"postalCode": "10021-3100" “邮政编码”:“ 10021-3100”
}, },
"phoneCalls": [ “电话”:[
{ {
"type": "home", “ type”:“家”,
"number": "212 555-1234", “ number”:“ 212 555-1234”,
"duration": "32" “持续时间”:“ 32”
}, },
{ {
"type": "office", “ type”:“办公室”,
"number": "646 555-4567", “ number”:“ 646 555-4567”,
"duration": "79" “持续时间”:“ 79”
} }
] ]
} }

Every x second the Json file is updated with random calls added to the document, i need to use those information. Json文件每隔x秒就会使用添加到文档中的随机调用进行更新,我需要使用这些信息。

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. 我不确定如何连接到此本地Web服务,并从此更新文档中检索此信息,我想使用JAVA,但请告诉我是否有更好的解决方案。

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. 请参阅此示例,了解如何在Java中通过http从给定的URL返回JSONObject。 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) . 之后,您可以使用JSONObject类的方法(如getInt(String)getString(String)检索数据。 You can obtain nested objects with getJSONObject(String) . 您可以使用getJSONObject(String)获得嵌套对象。 All by providing a string with the name of the field/object as parameter. 通过提供带有字段/对象名称作为参数的字符串来完成所有操作。

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

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