請參閱此示例以瞭解如何通過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)
獲取嵌套對象。所有這些都通過提供字段/字段名稱作爲參數。
您提供JSON字符串的Web服務是否也將JSON字符串推送到您的Web服務? – shinjw 2014-09-19 15:51:21