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

jogvjijk  于 12个月前  发布在  Java
关注(0)|答案(1)|浏览(138)

我有下面的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时是可以预期的。这意味着服务器已经收到了你的查询,并正在处理它。我们需要不断检查请求的状态,通过重试在202响应中发送的新URL,直到你得到HTTP 200。但我不知道我怎么能做到这一点?

bkkx9g8r

bkkx9g8r1#

是的,您需要不断询问远程资源任务是否已完成。
202是非承诺性的,这意味着HTTP无法稍后发送指示处理请求的结果的异步响应。
我看到您还在使用“裸金属”实用程序,如HttpURLConnection,这让我相信您没有任何库支持重试HTTP调用。
在这种情况下,你可以做的是生成一个新线程,可能使用ExecutorServicesubmit/execute一个简单循环的任务,例如。

while (!Thread.interrupted()) { ... }

字符串
调用您的URL,直到收到HTTP_OK
一具 backbone 可能是

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;
}

相关问题