对于在 Java 中获取 http 响应代码 202 的异步 http api 请求

For asynchronous http api request getting http responce code 202 in Java

我有以下 DSS 到 url 的 http 连接:

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 200HTTP_OK 那么我可以获取数据并插入数据库 table. 但现在问题是在处理过程中,我现在处于 Got http error code as 202 之间,即 HTTP_ACCEPTED,因此我无法将此数据处理到数据库 table.

我认为在请求异步时 HTTP 202 是可以预期的。这意味着服务器已收到您的查询并正在处理它。我们需要通过重试 202 响应中发送的新 URL 来不断检查请求的状态,直到您获得 HTTP 200。但我不知道我该怎么做?

嗯,是的,你需要不断询问远程资源任务是否已经完成。

202 is non-committal, meaning that there is no way for the HTTP to later send an asynchronous response indicating the outcome of processing the request.

我看到您也在使用“裸机”实用程序,例如 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;
}