如何通过预定义的秒数终止AsyncTask请求

时间:2015-12-09 13:32:54

标签: java android

我正在尝试创建处理程序,以便在服务器没有响应20秒的情况下终止http请求。我想知道从Async任务类中做到这一点的最佳方法是什么。

这是我的代码:

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


}

2 个答案:

答案 0 :(得分:1)

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

HttpUrlConnection有一个setConnectionTimeout()方法就是这样做的。

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

答案 1 :(得分: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;
  }