2014-09-19 23 views
0

我需要一個學校項目的幫助,我需要連接到一個提供JSON文檔的Web服務,每3或4秒更新一次,使用它並使用一些包含的信息。該JSON看起來是這樣的:使用提供更新JSON對象的Web服務

{ 「名字」: 「約翰」,
「姓氏」: 「史密斯」,
「的IsAlive」:真實,
「年齡」:25,
「height_cm 「:167.6,
「地址」:{
「的StreetAddress」: 「21街2號」,
「城市」: 「紐約」,
「狀態」: 「NY」,
「郵編」: 「10021-3100」
},
「電話中」:[
{
「類型」: 「家」,
「號」: 「212 555-1234」,
「持續時間」: 「32」
},
{
「類型」: 「辦公室」,
「號」: 「646 555-4567」,
「持續時間」: 「79」
}
]
}

每隔x秒鐘Json文件就會隨着添加到文檔中的隨機調用而更新, 我需要使用這些信息。

我不知道如何連接到這個本地的Web服務,並從這個更新的文檔檢索這個信息,我想使用JAVA,但讓我知道是否有更好的解決方案。

感謝您提供給我的所有提示。

+0

您提供JSON字符串的Web服務是否也將JSON字符串推送到您的Web服務? – shinjw 2014-09-19 15:51:21

回答

0

請參閱此示例以瞭解如何通過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)獲取嵌套對象。所有這些都通過提供字段/字段名稱作爲參數。