Android httprequest处理时间延迟直到有响应
我有一个应用程序调用函数将JSON对象发送到REST API,我的问题是如何处理时间延迟并重复此函数,直到在网络连接中断的情况下收到服务器的响应?? 我尝试使用处理程序,但我不知道当我得到响应时如何停止 以下是单击按钮时调用的我的函数:Android httprequest处理时间延迟直到有响应,android,handler,postdelayed,Android,Handler,Postdelayed,我有一个应用程序调用函数将JSON对象发送到REST API,我的问题是如何处理时间延迟并重复此函数,直到在网络连接中断的情况下收到服务器的响应?? 我尝试使用处理程序,但我不知道当我得到响应时如何停止 以下是单击按钮时调用的我的函数: protected void sendJson(final String name, final String email, final String homepage,final Long unixTime,final String bundleId) {
protected void sendJson(final String name, final String email, final String homepage,final Long unixTime,final String bundleId) {
Thread t = new Thread() {
public void run() {
Looper.prepare(); //For Preparing Message Pool for the child Thread
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
HttpResponse response;
JSONObject json = new JSONObject();
//creating meta object
JSONObject metaJson = new JSONObject();
try {
HttpPost post = new HttpPost("http://util.trademob.com:5000/cards");
metaJson.put("time", unixTime);
metaJson.put("bundleId", bundleId);
json.put("name", name);
json.put("email", email);
json.put("homepage", homepage);
//add the meta in the root object
json.put("meta", metaJson);
StringEntity se = new StringEntity( json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
String authorizationString = "Basic " + Base64.encodeToString(
("tester" + ":" + "tm-sdktest").getBytes(),
Base64.NO_WRAP); //Base64.NO_WRAP flag
post.setHeader("Authorization", authorizationString);
response = client.execute(post);
String temp = EntityUtils.toString(response.getEntity());
Toast.makeText(getApplicationContext(), temp, Toast.LENGTH_LONG).show();
} catch(Exception e) {
e.printStackTrace();
}
Looper.loop(); //Loop in the message queue
}
};
t.start();
}
我将实现一个监听器接口,您可以将其传递给您的方法,然后根据响应错误/成功,从监听器调用适当的方法,以便在出现错误时再次运行API调用。您让事情变得更复杂,我对android有点陌生,请您编写一些代码,谢谢