1

我有一个应用程序调用函数将 JSON 对象发送到 REST API,我的问题是如何处理时间延迟并重复此函数,直到在网络连接中断的情况下得到服务器的响应?我尝试使用处理程序,但当我得到响应时我不知道如何停止它!!!!

这是单击按钮时调用的函数:

 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();      
}
4

0 回答 0