具有已定义超时的Java HTTP客户端请求 [英] Java HTTP Client Request with defined timeout

查看:125
本文介绍了具有已定义超时的Java HTTP客户端请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的云中为多个服务器制作BIT(内置测试)。我需要请求在大超时时失败。

I would like to make BIT (Built in tests) to a number of server in my cloud. I need the request to fail on large timeout.

我应该如何使用java?

How should I do this with java?

尝试某事如下所示似乎不起作用。

Trying something like the below does not seem to work.

public class TestNodeAliveness {
 public static NodeStatus nodeBIT(String elasticIP) throws ClientProtocolException, IOException {
  HttpClient client = new DefaultHttpClient();
  client.getParams().setIntParameter("http.connection.timeout", 1);

  HttpUriRequest request = new HttpGet("http://192.168.20.43");
  HttpResponse response = client.execute(request);

  System.out.println(response.toString());
  return null;
 }


 public static void main(String[] args) throws ClientProtocolException, IOException {
  nodeBIT("");
 }
}

- 编辑:澄清正在使用的库 - -

-- Clarify what library is being used --

我正在使用来自apache的httpclient,这是相关的pom.xml部分

I'm using httpclient from apache, here is the relevant pom.xml section

 <dependency>
   <groupId>org.apache.httpcomponents</groupId>
   <artifactId>httpclient</artifactId>
   <version>4.0.1</version>
   <type>jar</type>
 </dependency>


推荐答案

import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

...

    // set the connection timeout value to 30 seconds (30000 milliseconds)
    final HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, 30000);
    client = new DefaultHttpClient(httpParams);

这篇关于具有已定义超时的Java HTTP客户端请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆