2016-07-15 1 views
2

У меня есть некоторые данные, которые будут отправлены из приложения Android на сервер через http (s). Его необходимо отправить в порядке.Повторите HTTP (S) POST до тех пор, пока они не добьются успеха на Android

Существует ли уже существовавший способ очередности HTTP-запросов (для одного и того же сервера) и повторная попытка их завершения (не обязательно успешно)?

Моя проблема заключается в том, что http-запросы могут потерпеть неудачу, если нет покрытия сети. Должна быть какая-то форма экспоненциального отступления или прослушиватель (для повторного подключения сети), чтобы вызвать повторную попытку заголовка очереди.

Я могу написать это сам, но я хочу проверить, что я не изобретаю колесо.

+2

Использование залп библиотека. У него лучшая политика повторения. –

+2

Другая возможность: ** Дооснащение **. –

+1

Может ли загрузка быть в фоновом режиме? Если это так, вы можете использовать что-то вроде volley или retrofit для фактической загрузки данных в сочетании с ресивером 'android.net.conn.CONNECTIVITY_CHANGE', который будет загружать данные в очередь, когда сеть возвращается. У меня есть аналогичный механизм в моем приложении, и он работает блестяще. – Neil

ответ

1

Есть несколько вариантов, чтобы сделать это:

Volley:

RequestQueue queue = Volley.newRequestQueue(ctx); // ctx is the context 
StringRequest req = new StringRequest(Request.Method.GET, url, 
    new Response.Listener<String>() { 
     @Override 
     public void onResponse(String data) { 
      // We handle the response       
     } 
    }, 
    new Response.ErrorListener() { 
     @Override 
      // handle response 
     } 
    ); 
queue.add(req); 

OkHttp:

OkHttpClient client = new OkHttpClient(); 
client.newCall(request).enqueue(new Callback() { 
    @Override 
    public void onFailure(Request request, IOException e) { 
     // Handle error 
    } 

    @Override 
     public void onResponse(Response response) throws IOException { 
     //handle response 
    } 
}); 

Или вы можете использовать счетчик в ваших запросов, и пусть сервер заказывает их. Если вам интересно узнать больше об Android Http-библиотеках, я написал сообщение недавно. Посмотрите here

+0

Спасибо, что я не знал о OkHttp. Волейбол был чем-то, что я рассматривал для упаковки, чтобы сделать http-post-retrying-queue. – fadedbee

+0

Очередь должна обрабатывать ошибку/сбой, просто повторяя (навсегда или в течение 24 часов) с отступлением. – fadedbee

0

Я использую этот метод для post https. Я успешно выполняю все условия.

private class AysncTask extends AsyncTask<Void,Void,Void> 
    { 
     private ProgressDialog regDialog=null; 
     @Override 
     protected void onPreExecute() 
     { 
      super.onPreExecute(); 
      regDialog=new ProgressDialog(this); 
      regDialog.setTitle(getResources().getString(R.string.app_name)); 
      regDialog.setMessage(getResources().getString(R.string.app_pleasewait)); 
      regDialog.setIndeterminate(true); 
      regDialog.setCancelable(true); 
      regDialog.show(); 
     }  
     @Override 
     protected Void doInBackground(Void... params) { 
      try 
      { 
       new Thread(new Runnable() { 
        @Override 
        public void run() { 
         ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>(); 



         postParameters.add(new BasicNameValuePair("param1", 
           paramvalue)); 
        postParameters.add(new BasicNameValuePair("param2", 
           paramvalue)); 




         String response = null; 
         try { 
          response = SimpleHttpClient 
            .executeHttpPost("url.php", 
              postParameters); 
          res = response.toString(); 

          return res; 

         } catch (Exception e) { 
          e.printStackTrace(); 
          errorMsg = e.getMessage(); 
         } 
        } 
       }).start(); 
       try { 
        Thread.sleep(3000); 


       // error.setText(resp); 
        if (null != errorMsg && !errorMsg.isEmpty()) { 

        } 
       } catch (Exception e) { 
       } 

      } 
      catch (Exception e) 
      { 
       e.printStackTrace(); 
      } 
      return null; 
     } 

     @Override 
     protected void onPostExecute(Void result) 
     { 
      super.onPostExecute(result); 
      if(regDialog!=null) 
      { 

       regDialog.dismiss(); 

      //do you code here you want 

       } 

    // do what u do 
    } 

SimpleHttpClient.java

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.net.URI; 
import java.util.ArrayList; 

import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.conn.params.ConnManagerParams; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.params.HttpConnectionParams; 
import org.apache.http.params.HttpParams; 

public class SimpleHttpClient { 
/** The time it takes for our client to timeout */ 
    public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds 

    /** Single instance of our HttpClient */ 
    private static HttpClient mHttpClient; 

    /** 
    * Get our single instance of our HttpClient object. 
    * 
    * @return an HttpClient object with connection parameters set 
    */ 
    private static HttpClient getHttpClient() { 
    if (mHttpClient == null) { 
     mHttpClient = new DefaultHttpClient(); 
     final HttpParams params = mHttpClient.getParams(); 
     HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT); 
     HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT); 
     ConnManagerParams.setTimeout(params, HTTP_TIMEOUT); 
    } 
    return mHttpClient; 
    } 

    public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception { 
    BufferedReader in = null; 
    try { 
     HttpClient client = getHttpClient(); 
     HttpPost request = new HttpPost(url); 
     UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters); 
     request.setEntity(formEntity); 
     HttpResponse response = client.execute(request); 
     in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 

     StringBuffer sb = new StringBuffer(""); 
     String line = ""; 
     String NL = System.getProperty("line.separator"); 
     while ((line = in.readLine()) != null) { 
     sb.append(line + NL); 
     } 
     in.close(); 

     String result = sb.toString(); 
     return result; 
    } 
    finally { 
     if (in != null) { 
     try { 
      in.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     } 
    } 
    } 


    public static String executeHttpatch(String url, ArrayList<NameValuePair> postParameters) throws Exception { 
    BufferedReader in = null; 
    try { 
     HttpClient client = getHttpClient(); 
     HttpPost request = new HttpPost(url); 
     UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters); 
     request.setEntity(formEntity); 
     HttpResponse response = client.execute(request); 
     in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 

     StringBuffer sb = new StringBuffer(""); 
     String line = ""; 
     String NL = System.getProperty("line.separator"); 
     while ((line = in.readLine()) != null) { 
     sb.append(line + NL); 
     } 
     in.close(); 

     String result = sb.toString(); 
     return result; 
    } 
    finally { 
     if (in != null) { 
     try { 
      in.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     } 
    } 
    } 

    /** 
    * Performs an HTTP GET request to the specified url. 
    * 
    * @param url The web address to post the request to 
    * @return The result of the request 
    * @throws Exception 
    */ 
    public static String executeHttpGet(String url) throws Exception { 
    BufferedReader in = null; 
    try { 
     HttpClient client = getHttpClient(); 
     HttpGet request = new HttpGet(); 
     request.setURI(new URI(url)); 
     HttpResponse response = client.execute(request); 
     in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 

     StringBuffer sb = new StringBuffer(""); 
     String line = ""; 
     String NL = System.getProperty("line.separator"); 
     while ((line = in.readLine()) != null) { 
     sb.append(line + NL); 
     } 
     in.close(); 

     String result = sb.toString(); 
     return result; 
    } 
    finally { 
     if (in != null) { 
     try { 
      in.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     } 
    } 
    } 
} 
Смежные вопросы