【问题标题】:Retry HTTP(S) POSTs until they succeed on Android重试 HTTP(S) POST,直到它们在 Android 上成功
【发布时间】:2016-11-18 07:56:09
【问题描述】:

我有一些数据将通过 http(s) 从 Android 应用程序发送到服务器。需要按顺序发送。

是否已经存在一种将 http 请求(针对同一服务器)排队并重试它们直到它们完成(不一定成功)的方法?

我的问题是,如果没有网络覆盖,http 请求可能会失败。应该有某种形式的指数回退,或者一个监听器(用于网络重新连接)来提示重试队列的头部。

我可以自己写这个,但我想确认我没有重新发明轮子。

【问题讨论】:

  • 使用 volley 库。它有最好的重试策略。
  • 另一种可能是改造
  • 上传可以在后台进行吗?如果是这样,您可以使用诸如 volley 或改造之类的东西来实际上传数据,并结合android.net.conn.CONNECTIVITY_CHANGE 接收器,该接收器将在网络返回时上传排队的数据。我的应用程序中有一个类似的机制,并且效果很好。
  • 看看 Sinan Kozak 在retry requests with Retrofit的回答
  • 改装看起来很棒。我会在此基础上再接再厉。

标签: android http https queue


【解决方案1】:

有几种选择:

凌空抽射

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

【讨论】:

  • 谢谢 我不知道 OkHttp。 Volley 是我考虑包装成 http-post-retrying-queue 的东西。
  • 队列应该通过回退重试(永久或 24 小时)来处理错误/失败。
【解决方案2】:

我正在使用此方法发布 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();
        }
        }
    }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-25
    • 1970-01-01
    • 2016-02-16
    • 1970-01-01
    • 2021-11-10
    • 2014-10-01
    相关资源
    最近更新 更多