具有定义超时的Java HTTP客户端请求

我想对我的云中的许多服务器进行BIT(内置测试)。我需要大超时失败的请求。


我应该如何用Java做到这一点?


尝试以下操作似乎无效。


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

 }

}

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


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


 <dependency>

   <groupId>org.apache.httpcomponents</groupId>

   <artifactId>httpclient</artifactId>

   <version>4.0.1</version>

   <type>jar</type>

 </dependency>


回首忆惘然
浏览 374回答 3
3回答

MYYA

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;...&nbsp; &nbsp; // set the connection timeout value to 30 seconds (30000 milliseconds)&nbsp; &nbsp; final HttpParams httpParams = new BasicHttpParams();&nbsp; &nbsp; HttpConnectionParams.setConnectionTimeout(httpParams, 30000);&nbsp; &nbsp; client = new DefaultHttpClient(httpParams);

慕沐林林

看来您正在使用HttpClient API,对此我一无所知,但是您可以使用核心Java编写类似的内容。try {&nbsp; &nbsp;HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();&nbsp; &nbsp;con.setRequestMethod("HEAD");&nbsp; &nbsp;con.setConnectTimeout(5000); //set timeout to 5 seconds&nbsp; &nbsp;return (con.getResponseCode() == HttpURLConnection.HTTP_OK);} catch (java.net.SocketTimeoutException e) {&nbsp; &nbsp;return false;} catch (java.io.IOException e) {&nbsp; &nbsp;return false;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java