[英]CloseableHttpClient throws java.net.SocketTimeoutException: Read timed out
我嘗試使用 get 請求從NSE - India檢索期權鏈數據:
https://www.nseindia.com/api/option-chain-equities?symbol=INFY
當從 postman 客戶端/chrome 瀏覽器請求時,響應在 650 毫秒內返回
我試圖從 Apache http 客戶端檢索相同的數據
public static void main(String args[]) {
int timeout = 3;
RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000)
.setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build();
CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
try {
// HttpGet getRequest = new HttpGet("https://reqres.in/api/users?page=2");
HttpGet getRequest = new HttpGet("https://www.nseindia.com/api/option-chain-equities?symbol=INFY");
getRequest.addHeader("accept", "*/*");
HttpResponse response = httpClient.execute(getRequest);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
throw new RuntimeException("Failed with HTTP error code : " + statusCode);
}
HttpEntity httpEntity = response.getEntity();
String output = EntityUtils.toString(httpEntity);
System.out.println(output);
JAXBContext jaxbContext = JAXBContext.newInstance(Records.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Records records = (Records) jaxbUnmarshaller.unmarshal(new StringReader(output));
System.out.println(records);
} catch (Exception e) {
e.printStackTrace();
}
}
它拋出java.net.SocketTimeoutException: Read timed out但我相信設置的時間足以獲取數據。 我嘗試了另一個獲取請求
需要一些關於如何調試這種情況的建議。
好的,看起來 HTTPS 連接已成功,您已成功發送請求。
一種可能的解釋是 nseindia.com 故意“慢走”您的要求。 這是一些網站用來阻止不需要的請求的策略; 例如,違反其使用條款的自動請求。 這個想法是他們需要......非常......很長......時間......做出響應,以便提交請求的自動化被完全阻止或嚴重限制他們可以做的事情。
另一種可能性是您的網絡基礎設施存在問題,該問題正在“黑洞”一些從 nseindia.com 返回的網絡數據包。 (您沒有說您是否在運行 web 瀏覽器的同一台機器上運行 Java 代碼。或者如果您的 web 瀏覽器正在通過代理。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.