我创建了以下用于判断连接状态的函数:

private void checkConnectionStatus() {
    HttpClient httpClient = new DefaultHttpClient();

    try {
      String url = "http://xxx.xxx.xxx.xxx:8000/GaitLink/"
                   + strSessionString + "/ConnectionStatus";
      Log.d("phobos", "performing get " + url);
      HttpGet method = new HttpGet(new URI(url));
      HttpResponse response = httpClient.execute(method);

      if (response != null) {
        String result = getResponse(response.getEntity());
        ...

当我关闭服务器进行测试时,执行程序排了很长时间的队

HttpResponse response = httpClient.execute(method);

有没有人知道如何设置超时以避免等待时间过长?

谢谢!

推荐答案

在我的示例中,设置了两个超时.连接超时抛出java.net.SocketTimeoutException: Socket is not connected,套接字超时抛出java.net.SocketTimeoutException: The operation timed out.

HttpGet httpGet = new HttpGet(url);
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);
HttpResponse response = httpClient.execute(httpGet);

如果要设置任何现有HTTPClient(例如DefaultHttpClient或AndroidHttpClient)的参数,可以使用函数setParams().

httpClient.setParams(httpParameters);

Java相关问答推荐

收听RDX中用户数据的变化

Maven Google Sheets版本问题

如何使用CSS为选定但未聚焦的表格行设置背景 colored颜色 ?

如果给定层次 struct 级别,如何从其预序穿越构造n元树

是否需要关闭Executors返回的执行器.newVirtualThreadPerTaskExecutor()?

Springdoc Whitelabel Error Page with Spring V3

Domino Designer 14中的保存代理添加了重影库

在执行流和相关操作时,使用Java泛型为2个方法执行相同的操作,但对象不同

有没有可能在时间范围内得到多种解决方案?

在macOS上读取文件会导致FileNotFound,即使文件存在(并且具有权限)

在Spring Boot应用程序中,server.port=0的默认端口范围是多少?

错误:未找到扩展元素在JBossEAP 7.2中安装FUSE时出错

有谁能帮我修一下这个吗?使输出变得更加整洁

使用SWIG将C++自定义单元类型转换为基本Java类型

有没有办法在o(log(N))中以系统的方式将数组中的小块元素复制和移动到新增长的数组中的左侧?

在打开搜索结果时,如何让Eclipse打开整个文件?

Java递归泛型是否可以被视为继承和重写的语法糖

Intellij 2023 IDE:始终在顶部显示菜单栏

如何使用命令行为Java应用程序生成烟雾测试用例

Hibernate 命名策略导致 Java Spring Boot 应用程序中出现未知列错误