1、配置超时
int timeout = 5; RequestConfig config = RequestConfig.custom() .setConnectTimeout(timeout * 1000) .setConnectionRequestTimeout(timeout * 1000) .setSocketTimeout(timeout * 1000).build(); CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
使用先前定义的客户端,与主机的连接将在5秒内超时,如果建立连接但没有收到数据,则超时也将是5秒。
请注意,连接超时将导致org.apache.http.conn.ConnectTimeoutException被抛出,而套接字超时将导致一个java.net.SocketTimeoutException。
2、Https请求
@Test public void givenIgnoringCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws Exception { SSLContext sslContext = new SSLContextBuilder() .loadTrustMaterial(null, (certificate, authType) -> true).build(); CloseableHttpClient client = HttpClients.custom() .setSSLContext(sslContext) .setSSLHostnameVerifier(new NoopHostnameVerifier()) .build(); HttpGet httpGet = new HttpGet(HOST_WITH_SSL); httpGet.setHeader("Accept", "application/xml"); HttpResponse response = client.execute(httpGet); assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); }