2016-07-15 5 views
2

私はいくつかのデータをHTTP経由でAndroidアプリからサーバーに送信します。順序通りに送信する必要があります。Androidで成功するまでHTTP(S)POSTを再試行してください

(同じサーバーの)HTTP要求をキューに入れ、完了するまで再試行する方法はありますか(必ずしも成功するとは限りません)。

私の問題は、ネットワークのカバレッジがないとhttp要求が失敗する可能性があることです。キューの先頭の再試行を促すリスナー(ネットワーク再接続用)や、指数関数的なバックオフが必要です。

私はこれを自分で書くことができますが、私はホイールを再発明していないことを確認したいと思います。

+2

使用ボレーライブラリ。最高の再試行ポリシーがあります。 –

+2

もう一つの可能​​性は** Retrofit **です。 –

+1

アップロードをバックグラウンドで実行できますか?もしそうならば、volleyやretrofitのようなものを使って、ネットワークが復帰したときにキューに入れられたデータをアップロードする 'android.net.conn.CONNECTIVITY_CHANGE'レシーバと組み合わせてデータを実際にアップロードすることができます。私は私のアプリにも同様の仕組みを持っていて、うまく機能します。 – Neil

答えて

1

それを行うにはいくつかのオプションがあります。

ボレー:OkHttp

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); 

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を知らなかった。 Volleyは、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(); 
     } 
     } 
    } 
    } 
} 
関連する問題