baifaxiaoyao 2012-09-18 07:16 采纳率: 100%
浏览 4399
已采纳

使用Java,如何给Android设置 HttpResponse超时?

为了检查网络连接的情况,我创建了下边的方法:

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

有人知道怎么设置超时来避免等待太长的时间吗?
谢谢!

  • 写回答

3条回答

  • yizhenbeifeng 2012-09-18 07:36
    关注

    在我的示例中有两个超时的设置。连接超时声明抛出异常"java.net.SocketTimeoutException: Socket is not connected",Socket超时是"java.net.SocketTimeoutException: The operation timed out".

    HttpGet httpGet = new HttpGet(url);
    HttpParams httpParameters = new BasicHttpParams();
    int timeoutConnection = 3000;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    int timeoutSocket = 5000;
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    
    DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
    HttpResponse response = httpClient.execute(httpGet);
    

    如果你想给任何存在的HTTPClient(如DefaultHttpClient 或AndroidHttpClient)设置参数,你可以使用 setParams()方法。

    httpClient.setParams(httpParameters);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考