【问题标题】:How to check Internet connectivity Timeout for apache client in android如何在 android 中检查 apache 客户端的 Internet 连接超时
【发布时间】:2014-05-31 03:07:47
【问题描述】:

我有一个 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;
    }

【问题讨论】:

  • 如何查看?或者如何设置?
  • doInBackground 与您的问题有什么关系?你有一些代码可以抓取一个谷歌页面,这确实是一个很好的方法来检查你是否有互联网连接。 (您没有告诉您在哪个线程或异步任务中使用它,但并不重要)。如果没有互联网连接,则请求超时。非常清楚。现在有什么问题?
  • @MartinKonecny ..... 如何设置 :) ... 有什么想法吗?
  • @greenapps ..... 是的,如果没有互联网连接,则连接超时,但我希望连接发生超时,说等到 10 秒,然后超时......在重试之间再次连接......希望我很清楚!

标签: java android apache


【解决方案1】:

您必须为此构建自定义 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();
        }
    }
}

作为最佳实践,我强烈建议使用 VolleyRetrofit 作为网络库。

来源:java2s

【讨论】:

  • HttpProtocolParams.setUserAgent(params, "Mozilla/5.0 (Linux; U; Android 2.2.1;"); ....mean 是什么意思?...是否仅用于检查 Android 2.2.1 的连接性?
  • @CasperSky 用于服务器端验证,您的 rest api 提供程序过滤器将检查用户代理是否有效!
  • @CasperSky 告别这个老旧的越野车 Apis,向 volley 或 Retrofit 打个招呼,因为它只专注于您需要的内容和高效的优化代码!
猜你喜欢
  • 2012-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-19
相关资源
最近更新 更多