如何检查android中的apache客户端的Internet连接超时

时间:2014-05-31 03:07:48

标签: java android apache

我有一个Android客户端代码(我在这里检查internetconnection-doInBackground的超时) ::

public static void isNetworkAvailable(Context context){
    HttpGet httpGet = new HttpGet("http://www.google.com");
    HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used.
    int timeoutConnection = 3000;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = 5000;
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

    DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
    try{
        Log.d(TAG, "Checking network connection...");
        httpClient.execute(httpGet);
        Log.d(TAG, "Connection OK");
        return;
    }
    catch(ClientProtocolException e){
        e.printStackTrace();
    }
    catch(IOException e){
        e.printStackTrace();
    }

    Log.d(TAG, "Connection unavailable");
}

我的问题 ::如何检查我的Apache客户端的超时


我的Apache代码(doInBackground) ::

protected Void doInBackground(String... urls) {
        JSONObject jsonObject;  
        JSONArray jsonArrayTable;
        final HttpClient Client = new DefaultHttpClient();
        try {
            publishProgress(1);
            publishProgress(2);
            getPlaceNameFromMapQuestApi();

            mDbHelper = new DatabaseHandler(context);
            db = mDbHelper.getWritableDatabase();//Start the Database Transaction
            db.beginTransaction();//Start the Database Transaction

            HttpGet httpget = new HttpGet(URL);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            Content = Client.execute(httpget, responseHandler);
            jsonObject = new JSONObject(Content);   
            //Get Data from from JSON ans perform Insertion
            parseTables(jsonObject);
            if(isDistanceCal==true) distanceCalculation();  
            db.setTransactionSuccessful();//Commit the Transaction
            isDownloadAsynTaskSucceed=true;//Set this flag so that i can start the next activity
        } catch (Exception e) {
            e.printStackTrace();
            if(isErr==false){
                errMsg=e.toString();
                isErr=true;
            }
            publishProgress(0);// This is necessary to make sure that alert is popped in opprogressupdate 
        }finally{
            db.endTransaction();//End the Database Transaction
            db.close();//close the database connection
        }
        return null;
    }

1 个答案:

答案 0 :(得分:0)

您必须为该

构建自定义CustomHttpClient
class CustomHttpClient {
    private static HttpClient customHttpClient;

    public static synchronized HttpClient getHttpClient() {
        if (customHttpClient != null) {
            return customHttpClient;
        }
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params,
                HTTP.DEFAULT_CONTENT_CHARSET);
        HttpProtocolParams.setUseExpectContinue(params, true);
        HttpProtocolParams.setUserAgent(params,
                "Mozilla/5.0 (Linux; U; Android 2.2.1;");
        ConnManagerParams.setTimeout(params, 1000);
        HttpConnectionParams.setConnectionTimeout(params, 5000);
        HttpConnectionParams.setSoTimeout(params, 10000);

        SchemeRegistry schReg = new SchemeRegistry();
        schReg.register(new Scheme("http", PlainSocketFactory
                .getSocketFactory(), 80));
        schReg.register(new Scheme("https",
                SSLSocketFactory.getSocketFactory(), 443));
        ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
                params, schReg);
        customHttpClient = new DefaultHttpClient(conMgr, params);
        return customHttpClient;
    }

    public Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException();
    }
}

public class Test extends Activity {
    private HttpClient httpClient;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        httpClient = CustomHttpClient.getHttpClient();
        getHttpContent();
    }

    public void getHttpContent() {
        try {
            HttpGet request = new HttpGet("http://www.google.com/");
            HttpParams params = request.getParams();
            HttpConnectionParams.setSoTimeout(params, 60000); // 1 minute
            request.setParams(params);
            Log.v("connection timeout", String.valueOf(HttpConnectionParams
                    .getConnectionTimeout(params)));
            Log.v("socket timeout",
                    String.valueOf(HttpConnectionParams.getSoTimeout(params)));

            String page = httpClient.execute(request,
                    new BasicResponseHandler());
            System.out.println(page);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

作为最佳做法,我强烈建议您使用 Volley Retrofit 作为网络库。

来源:java2s