Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/232.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
重试HTTP帖子,直到它们在Android上成功_Android_Http_Https_Queue - Fatal编程技术网

重试HTTP帖子,直到它们在Android上成功

重试HTTP帖子,直到它们在Android上成功,android,http,https,queue,Android,Http,Https,Queue,我有一些数据将通过http从Android应用程序发送到服务器。它需要按顺序发送 是否已经存在将http请求排队(针对同一服务器)并重试直到完成(不一定成功)的方法 我的问题是,如果没有网络覆盖,http请求可能会失败。应该有某种形式的指数退避,或者有一个侦听器(用于网络重新连接)来提示重试队列头 我可以自己写,但我想检查一下我是否在重新发明轮子。有几种方法可以做到这一点: 截击: RequestQueue queue = Volley.newRequestQueue(ctx); // ctx

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

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

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


我可以自己写,但我想检查一下我是否在重新发明轮子。

有几种方法可以做到这一点:

截击

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库的细节,我最近写了一篇文章。看一看

我正在使用此方法发布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
    }
私有类AYSNTASK扩展异步任务
{
private ProgressDialog regDialog=null;
@凌驾
受保护的void onPreExecute()
{
super.onPreExecute();
regDialog=新建ProgressDialog(此);
regDialog.setTitle(getResources().getString(R.string.app_name));
regDialog.setMessage(getResources().getString(R.string.app_pleasewait));
regDialog.setUndeterminate(true);
regDialog.setCancelable(true);
regDialog.show();
}       
@凌驾
受保护的Void doInBackground(Void…参数){
尝试
{
新线程(newrunnable()){
@凌驾
公开募捐{
ArrayList后参数=新的ArrayList();
添加(新的BasicNameValuePair(“参数1”),
参数值);
添加(新的BasicNameValuePair(“参数2”),
参数值);
字符串响应=null;
试一试{
响应=SimpleHttpClient
.executehttpost(“url.php”,
后参数);
res=response.toString();
返回res;
}捕获(例外e){
e、 printStackTrace();
errorMsg=e.getMessage();
}
}
}).start();
试一试{
睡眠(3000);
//错误。setText(resp);
if(null!=errorMsg&&!errorMsg.isEmpty()){
}
}捕获(例外e){
}
} 
捕获(例外e)
{
e、 printStackTrace();
}
返回null;
}
@凌驾
受保护的void onPostExecute(void结果)
{
super.onPostExecute(结果);
if(regDialog!=null)
{
regDialog.disclose();
//你想在这里编码吗
}
//做你该做的
}
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();
        }
        }
    }
    }
}
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStreamReader;
导入java.net.URI;
导入java.util.ArrayList;
导入org.apache.http.HttpResponse;
导入org.apache.http.NameValuePair;
导入org.apache.http.client.HttpClient;
导入org.apache.http.client.entity.UrlEncodedFormEntity;
导入org.apache.http.client.methods.HttpGet;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.conn.params.ConnManagerParams;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.apache.http.params.HttpConnectionParams;
导入org.apache.http.params.HttpParams;
公共类SimpleHttpClient{
/**客户端超时所需的时间*/
公共静态最终整数HTTP_超时=30*1000;//毫秒
/**我们的HttpClient的单个实例*/
专用静态HttpClient mHttpClient;
/**
*获取HttpClient对象的单个实例。
*
*@返回设置了连接参数的HttpClient对象
*/
私有静态HttpClient getHttpClient(){
if(mHttpClient==null){
mHttpClient=新的DefaultHttpClient();
最终HttpParams params=mHttpClient.getParams();
setConnectionTimeout(参数,HTTP_超时);
HttpConnectionParams.setSoTimeout(参数,HTTP_超时);
setTimeout(参数,HTTP_超时);
}
返回mHttpClient;
}
公共静态字符串executeHttpPost(字符串url、ArrayList后参数)引发异常{
BufferedReader in=null;
试一试{
HttpClient=getHttpClient();
HttpPost请求=新的HttpPost(url);
UrlEncodedFormEntity formEntity=新的UrlEncodedFormEntity(后参数);
请求。setEntity(formEntity);
HttpResponse response=client.execute(请求);
in=新的BufferedReader(新的InputStreamReader(response.getEntity().getContent());
StringBuffer sb=新的StringBuffer(“”);
字符串行=”;
字符串NL=System.getProperty(“line.separator”);
而((line=in.readLine())!=null){
sb.追加(行+NL);
}
in.close();
字符串结果=sb.toString();
返回结果;
}
最后{
if(in!=null){
试一试{
in.close();
}捕获(IOE异常){
e、 printStackTrace();
}
}
}
}
公共静态字符串executeHttpatch(字符串url、ArrayList后参数)引发异常{
BufferedReader in=null;
试一试{
HttpClient=getHttpClient();
HttpPost请求=新建