Android低连接取消异步http任务

时间:2014-12-09 04:35:35

标签: android networking android-asynctask

我有一个前台服务,可以从服务器运行我的所有上传/下载媒体文件(音频,视频,图片)。对于纯文本消息,我使用AsyncTask将消息发送到服务器。 在上传或下载邮件时,我会在邮件旁边显示一个进度条。

有人告诉我,在使用应用程序时,有时短信不会持续很长时间,进度条仍在旋转。 这就是我获取所有http请求的默认httpclient的方法。

private static DefaultHttpClient httpclient;  // my static httpclient

 public synchronized static DefaultHttpClient getNewHttpClient() {
    if(httpclient!=null){
        Log.d(TAG, "returning existing httpclient");
        return httpclient;      
    }

    try {
        Log.d(TAG, "creating new httpclient");

        KeyStore trustStore = KeyStore.getInstance(KeyStore
                .getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new SixDegreeSSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);


        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory
                .getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        HttpConnectionParams.setConnectionTimeout(params, 6 * 1000);
        ClientConnectionManager ccm = new ThreadSafeClientConnManager(
                params, registry);
        ConnManagerParams.setTimeout(params, 6000);
        httpclient=new DefaultHttpClient(ccm,params);
        return httpclient;
    } catch (Exception e) {
        Log.d(TAG, "Exception creating defaultClient");
        e.printStackTrace();
        return new DefaultHttpClient();
    } 
}

我使用了连接超时。我在AsyncTask的doInBackground方法中执行http post

@Override      
protected Boolean doInBackground(Object... argList) {       
try {           
HttpResponse response;   

if (this.requestMethod.equals(GET)) {

            HttpGet httpGet = new HttpGet(url);

            response = client.execute(httpGet);

        } else {

            HttpPost httpPost = new HttpPost(url);
            Log.d(TAG, "http post ");
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

            if (values != null) {
                for (Map.Entry<String, String> entry : values.entrySet()) {
                    nameValuePairs.add(new BasicNameValuePair(entry
                            .getKey(), entry.getValue()));
                }
                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
            }

            response = client.execute(httpPost);
            Log.d(TAG, "client execute");
        }

        /* setting a response code. */
        this.responseCode = response.getStatusLine().getStatusCode();

        returnflag = (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK);

        // Get the response
        StringBuilder str = new StringBuilder();
        try{
            if (returnflag) {
                BufferedReader rd = new BufferedReader(new InputStreamReader(
                    response.getEntity().getContent()));
                String line = "";               
                while ((line = rd.readLine()) != null) {
                str.append(line);
                }
                rd.close();
            }
        } finally{
            try{
                if(response.getEntity()!=null)
                    response.getEntity().consumeContent();  // consume the entity content
            } catch(IOException e){
                e.printStackTrace();
            }

        }

        this.responseString = str.toString();

    } catch (UnknownHostException ex) {
        System.out.println(TAG + " UnknownHostException ");
        ex.printStackTrace();
    } catch (IOException e) {
        System.out.println(TAG + " responseCode " + responseCode);
        e.printStackTrace();
        returnflag = false;
    }
    catch (NullPointerException ex){
        ex.printStackTrace();
        returnflag = false;
    }
    catch (IndexOutOfBoundsException ex)
    {   ex.printStackTrace();
        returnflag = false;
    } catch(Exception e){
        e.printStackTrace();
    }
    finally {

    }

    return returnflag;
    }

基于布尔返回标志,我在postExecute中处理结果,其中extendedHandler是我在活动中实现的接口的实例

protected void onPostExecute(Boolean result) {
if(result) {
        iRequester.onRequestSuccess(responseString, requestCode);
        if(extendedHandler != null) extendedHandler.onRequestSuccessExtended(responseString,    requestCode, this.tagData);
    }
    else {
        iRequester.onRequestFailure(responseCode, requestCode);
        if(extendedHandler != null) extendedHandler.onRequestFailureExtended(responseCode, requestCode, this.tagData);
    }

}

在此实现中,如果连接性较差,我应该如何处理它或在一定时间后取消尝试。我不确定是否只使用HttpConnectionParams.setSoTimeout会起作用。在取消任务之前,是否有任何方法可以知道消息是否已传递到服务器并且它只是在等待响应。 如果有任何需要进一步澄清,请告诉我。

谢谢

1 个答案:

答案 0 :(得分:0)

为什么不从服务器发回ACK以确认文本已成功接收?

JSON格式的确认结果:

{status: "ok")