[英]For asynchronous http api request getting http responce code 202 in Java
我有以下DSS
http 連接到 url:
private static HttpURLConnection connection(String urlSpec) {
HttpURLConnection connection = new URL(urlSpec).openConnection() as HttpURLConnection
connection.setRequestProperty('Prefer', 'respond-async, wait=60')
connection.setRequestProperty('Accept', 'application/json')
connection.setRequestMethod("POST")
connection.setRequestProperty("Content-Type", "application/json; utf-8")
connection.setDoOutput(true)
connection
}
下面是我的代碼的一部分,我正在檢查 http 響應,如果響應是 http 200
,即HTTP_OK
,那么我可以獲取數據並插入到數據庫表中。 但是現在問題出在處理過程中,我現在介於Got http error code as 202
即HTTP_ACCEPTED
之間,因此我無法將這些數據處理到數據庫表中。
我認為請求異步時可以預期HTTP 202
。 這意味着服務器已收到您的查詢並正在處理它。 我們需要通過重試在202
響應中發送的新URL
來繼續檢查請求的狀態,直到您得到HTTP 200
。 但我不知道我該怎么做?
好吧,是的,您需要不斷詢問遠程資源是否已完成任務。
202 是非承諾的,這意味着 HTTP 無法稍后發送異步響應來指示處理請求的結果。
我看到您還在使用“裸機”實用程序,例如HttpURLConnection
,這讓我相信您沒有任何庫支持重試 HTTP 調用。
在這種情況下,您可以做的是產生一個新線程,可能使用ExecutorService
,並submit
/ execute
一個簡單循環的任務,例如
while (!Thread.interrupted()) { ... }
調用您的 URL 直到收到HTTP_OK
。
骨架可能是
executorService.execute(() -> {
while (!Thread.interrupted()) {
// Return a valid value if `HTTP_OK`, otherwise `null`
final var result = callRemoteUrl(url);
if (result != null) {
callback.call(result);
return;
}
}
});
其中callback
是一個異步接收 HTTP 結果的實例。
while (true)
HttpURLConnection connection = connection("XXX.com")
if (connection.responseCode >= HTTP_SERVER_ERROR) {
// Server/internal error, we can't do anything
// Maybe throw a custom Exception.
break;
}
if (connection.responseCode != HTTP_OK) {
try {
// Adjust the delay between calls, in ms
Thread.sleep(1000);
} catch (final InterruptedException e) {
// Ignore
}
// Try again
continue;
}
println("Got http response code: ${connection.responseCode}, message: ${connection.responseMessage}")
log.info("Successful request to ${connection.getURL()}")
//println(connection.getInputStream().getText())
LazyMap json = jsonFromExtractionConnection(connection)
//Process the data from the response JSON and put it in the Map object for processing
tryToProcessMarketDataFromExtractionJson(json, ricMap)
// Filter the empty records out and take valid map from Data for inserting into DB table .
def validMap = ricMap.findAll { key, val ->
val.fs != null
}
insertIntoDb(validMap)
writeToFile(outFile, sql(ORACLE), Select.query, Arrays.asList(Data.COLUMNS))
// We're done, end the loop
break;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.