0

我有以下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那么我可以获取数据并插入到数据库表中。但是现在问题出在处理过程中,我现在介于两者之间Got http error code as 202HTTP_ACCEPTED因此我无法将这些数据处理到数据库表中。

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

4

1 回答 1

1

好吧,是的,您需要不断询问远程资源是否已完成任务。

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;
}
于 2021-02-03T16:16:41.713 回答