gpt4 book ai didi

java - 通过 HttpGet 持续连接?

转载 作者:行者123 更新时间:2023-12-01 12:49:54 25 4
gpt4 key购买 nike

嘿,我正在编写一个 Android 应用程序,它从 Node.js 服务器获取 JSON 对象。我的代码如下(我无权访问服务器代码)。有什么方法可以一致地检查服务器 JSON 对象的更改(如果他们更新它)?现在它只执行一次 GET 并停止。我希望能够查询更改并继续使用新的更新。想法?谢谢。

从 OnCreate() 调用:

new Read().execute("JSONkey");

这是我的读取 ASyncTask:

public class Read extends AsyncTask<String, Integer, String>{

@Override
protected String doInBackground(String...param) {
try {
read_json = getCoords();
httpText.append(read_json.toString() + "\n");
try{
}catch(Exception e){ e.printStackTrace(); }
JSONArray data = read_json.getJSONArray(param[0]);
for (int i = 0; i < data.length(); ++i){
JSONObject info = data.getJSONObject(i);
Coordinate pt = new Coordinate(info.getInt("point"), info.getString("name"), info.getDouble("lat"), info.getDouble("long"));
coords.put(pt.getPoint(), pt);
coordList.add(new GeoPoint(pt.getLat(),pt.getLong()));
}
return "Success"; //get "text"

} catch (Exception e){
return "Fail";
}
}

@Override
protected void onPostExecute(String result){

//Doing something with JSON

//new Read().execute("coords"); tried doing this, but I feel it is not right.


}
}

和 GetCoords():

 public JSONObject getCoords() 
throws ClientProtocolException, IOException, JSONException{
StringBuilder url = new StringBuilder(URL);

HttpGet get = new HttpGet(url.toString());

HttpResponse response = client.execute(get);
int status = response.getStatusLine().getStatusCode();
if(status == 200){
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject last = new JSONObject(data);
return last;
}else{
return null;
}

}

最佳答案

正确的方法是使用 WebSocket,但考虑到无法控制服务器端的限制,最好的选择是

将代码放入服务中:

http://developer.android.com/reference/android/app/IntentService.html

然后使用警报管理器安排定期更新。

http://developer.android.com/reference/android/app/AlarmManager.html

关于java - 通过 HttpGet 持续连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24311221/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com