如何按预定义的秒数终止异步任务请求[重复]

Posted

技术标签:

【中文标题】如何按预定义的秒数终止异步任务请求[重复]【英文标题】:how to teminate AsyncTask request by predefined number of seconds [duplicate] 【发布时间】:2016-03-14 19:16:19 【问题描述】:

我正在尝试创建处理程序,如果服务器在 20 秒内没有响应,它将终止 http 请求。我想知道从异步任务类中做到这一点的最佳方法是什么。

这是我的代码:

public class DBcontroller extends AsyncTask <List<NameValuePair>, Void, String>

    private static String url = "";
    private  Context context = null ;
    public AsyncResponse delegate= null;

    private PropertyReader propertyReader;
    private Properties properties;

    public DBcontroller(Context mycontext,AsyncResponse myresponse) 
        context = mycontext;
        delegate = myresponse;
        propertyReader = new PropertyReader(context);
        properties = propertyReader.getMyProperties("config.properties");
        url = properties.getProperty("url");
    



    @Override
    protected void onPreExecute() 
        super.onPreExecute();
        delegate.preProcess();



    

    @Override
    protected String doInBackground(List<NameValuePair>... params) 
        return postDataToServer(params[0]);
    

    @Override
    protected void onPostExecute(String resStr) 
        super.onPostExecute(resStr);
        delegate.handleResponse(resStr);

    

    private String postDataToServer(List<NameValuePair> list) 
        //check
        for (int i=0;i<list.size();i++)
            Log.d("responseString", list.get(i).toString());
        //check
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        String responseString = null;
        try 
            post.setEntity(new UrlEncodedFormEntity(list));
            HttpResponse response = client.execute(post);
            HttpEntity entity = response.getEntity();
            responseString = EntityUtils.toString(entity);
            Log.d("responseString1", responseString);

         catch (UnsupportedEncodingException e) 
            e.printStackTrace();
         catch (ClientProtocolException e) 
            e.printStackTrace();
         catch (IOException e) 
            e.printStackTrace();
        
        if(responseString!= null)
             Log.d("responseString2", responseString);
        return responseString;
    



【问题讨论】:

我想这可能会对你有所帮助***.com/questions/693997/… developer.android.com/about/versions/marshmallow/…。不推荐使用 HttpClient 使用 HttpUrlConnection 或者您可以使用 okhttp 来设置超时。你也可以去掉for循环中的一些代码可以把它们留在外面 【参考方案1】:

用途:

httpUrlConnection.setConnectTimeout(5000); // 5s timeout
httpUrlConnection.setReadTimeout(5000); 

您也可以发布一个处理程序,该处理程序将在您的 Url 连接上调用 disconnect():

    new Handler(Looper.getMainLooper()).postDelayed(new Runnable()
      @Override
      public void run() 
        httpUrlConnection.disconnect();
      
    , 5000);

[编辑]

HttpClient 到 Url 的转换伪代码 - 未经测试!

  @TargetApi(Build.VERSION_CODES.GINGERBREAD)
  public boolean postToServer(String url, String postData, StringBuilder resultData) throws IOException 
    URL at_url = new URL(url);
    int responseCode = 0;
    try 
      HttpURLConnection httpUrlConnection = (HttpURLConnection) at_url.openConnection();

      httpUrlConnection.setUseCaches(false);
      httpUrlConnection.setRequestProperty("User-Agent", "MyAgent");
      httpUrlConnection.setConnectTimeout(30000);
      httpUrlConnection.setReadTimeout(30000);

      httpUrlConnection.setRequestMethod("POST");
      httpUrlConnection.setDoOutput(true);

      OutputStream os = httpUrlConnection.getOutputStream();
      try 
        os.write(postData.getBytes(Charset.forName("UTF-8")));
       finally 
        os.flush();
        os.close();
      

      httpUrlConnection.connect();

      String response = "";
      responseCode = httpUrlConnection.getResponseCode();
      if (responseCode == 200) 
        InputStream is = httpUrlConnection.getInputStream();
        response = convertStreamToString(is);
        // Read is to get results
       else 
        InputStream is = httpUrlConnection.getErrorStream();
        response = convertStreamToString(is);
        // Read is to get error
      
      resultData.append(response);

    
    finally 
      // Cleanup
    
    return responseCode == 200;
  

【讨论】:

您有机会帮我用您在我的代码中建议的 httpurlconnection 替换我的 HttpClient 对象吗? @matant 我添加了一些代码,您应该可以轻松地适应您的需求。【参考方案2】:

http://developer.android.com/reference/java/net/HttpURLConnection.html

HttpUrlConnection 有一个 setConnectionTimeout ( ) 方法可以做到这一点。

HttpURLConnection http = (HttpURLConnection)     mURL.openConnection();
http.setConnectTimeout(15000); //timeout after 15 seconds

【讨论】:

以上是关于如何按预定义的秒数终止异步任务请求[重复]的主要内容,如果未能解决你的问题,请参考以下文章

Java如何实现任务超时处理

使用 XCTestExpectation 对异步函数进行单元测试,但它不会等待我设置的秒数

一些有价值bug产生的思考

活动丢失后终止异步任务

Linux计划任务实现按秒运行

如何在固定时间间隔后重复执行异步任务