[英]Consume web service providing updating JSON object
我需要一個學校項目的幫助,我需要連接到提供JSON文檔的Web服務,該文檔每3或4秒更新一次,使用它並使用其中包含的某些信息。 JSON如下所示:
{“ firstName”:“ John”,
“ lastName”:“ Smith”,
“ isAlive”:是的,
“年齡”:25歲,
“ height_cm”:167.6,
“地址”: {
“ streetAddress”:“ 21 2nd Street”,
“ city”:“ New York”,
“ state”:“ NY”,
“郵政編碼”:“ 10021-3100”
},
“電話”:[
{
“ type”:“家”,
“ number”:“ 212 555-1234”,
“持續時間”:“ 32”
},
{
“ type”:“辦公室”,
“ number”:“ 646 555-4567”,
“持續時間”:“ 79”
}
]
}
Json文件每隔x秒就會使用添加到文檔中的隨機調用進行更新,我需要使用這些信息。
我不確定如何連接到此本地Web服務,並從此更新文檔中檢索此信息,我想使用JAVA,但請告訴我是否有更好的解決方案。
感謝您提供的所有提示。
請參閱此示例,了解如何在Java中通過http從給定的URL返回JSONObject。 這包括對基本身份驗證的支持,您可能需要也可能不需要。
您要做的是使用計時器調用此方法,以根據需要刷新您的供稿。
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;
...其他進口
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());
}
之后,您可以使用JSONObject
類的方法(如getInt(String)
或getString(String)
檢索數據。 您可以使用getJSONObject(String)
獲得嵌套對象。 通過提供帶有字段/對象名稱作為參數的字符串來完成所有操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.