简体   繁体   English

如何等到 URL 在 Java 就绪?

[英]How to wait until URL is ready in Java?

I created method that reads bytes from an URL with image and writes it to the S3 bukcet.我创建了从带有图像的 URL 中读取字节并将其写入 S3 bukcet 的方法。

public void saveFileToStorage(String url, Long timestamp, Integer vehicleId) {
    try {
        URL link = new URL(url);
        Thread.sleep(1500);//wait until URL is ready for download
        byte[] contentBytes = IOUtils.toByteArray(link);
        Long contentLength = (long) contentBytes.length;
        repository.uploadFile(timestamp + ".jpg", link.openStream(), vehicleId.toString() + "/", contentLength);
    } catch (IOException | InterruptedException e) {
        log.error(e.getMessage() + " - check thread sleep time!");
        throw new RuntimeException(e);
    }

}

Repository:存储库:

public void uploadFile(String keyName, InputStream file, String folder, Long contentLength) {
    ObjectMetadata folderMetadata = new ObjectMetadata();
    folderMetadata.setContentLength(0);
    ObjectMetadata fileMetadata = new ObjectMetadata();
    fileMetadata.setContentLength(contentLength);
    s3client.putObject(bucketName, folder, new ByteArrayInputStream(new byte[0]), folderMetadata);
    s3client.putObject(new PutObjectRequest(bucketName, folder + keyName, file, fileMetadata));
}

My main problem with this method was the time of URL readiness, when I run the app it always threw a RuntimeException because the URL wasn't ready to read.我使用此方法的主要问题是 URL 准备就绪的时间,当我运行该应用程序时,它总是抛出 RuntimeException,因为 URL 尚未准备好读取。 After some tests where I was looking at the URL response time, I added Thread.sleep and after that the apps work fine, but the response time can vary and I still get these errors from time to time.在我查看 URL 响应时间的一些测试之后,我添加了 Thread.sleep,之后应用程序运行正常,但响应时间可能会有所不同,我仍然会不时遇到这些错误。 What is the best way to check if a URL is ready?检查 URL 是否准备就绪的最佳方法是什么? I'm trying to use the code below to check for readiness, but I can't figure out how to "wait" until the URL is ready to use我正在尝试使用下面的代码来检查是否准备就绪,但我不知道如何“等待”直到 URL 准备好使用

 public static boolean check(String URLName){
    try {
        HttpURLConnection.setFollowRedirects(false);
        HttpURLConnection con = (HttpURLConnection) new URL(URLName).openConnection();
        con.setRequestMethod("HEAD");
        return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
    }
    catch (Exception e) {
       return false;
    }

I would write the method something like this:我会这样写方法:

create and configure HttpURLConnection for GET requests
for retries in 0 ... N:
    try:
        connect
        if status code == 200:
            open and read connection input stream
            return
        else:
            if status code not retriable:
                fail
    catch FileNotFound:
        // noop
    catch IOException:
        fail
    sleep S seconds
fail
     

There some key differences between this and your approach.这与您的方法之间存在一些关键差异。

  • This doesn't do a HEAD.这不会做一个 HEAD。 That requires an extra round trip to the server.这需要额外往返服务器。 Just do a GET each time.每次只做一个 GET。
  • This doesn't retry for all status codes.这不会重试所有状态代码。 For example, if you got a 403 you shouldn't retry.例如,如果您收到 403,则不应重试。
  • This retries for a FileNotFound exception which you will get for a 404 response;这将重试 FileNotFound 异常,您将获得 404 响应; see the javadoc.请参阅javadoc。 It shoulkdn't retry for other IO exceptions... unless they are likely to succeed on retry.它不应该重试其他 IO 异常......除非它们很可能在重试时成功。
  • The max number of retries and delay between retries should be tuned.应调整重试的最大次数和重试之间的延迟。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何等到所有 Promise 都完成? - How to wait until all of Promise are fulfilled? 我如何才能等到所有 FCM 订阅完成 - How can I wait until all FCM subscriptions are done 如何在 Node.js 的 BigQuery 中等待查询完成 - How to wait until query is completed in BigQuery in Node.js 怎么才能等到Firebase Flutter 取回数据库数据呢? - How can I wait until Firebase Database data is retrieved in Flutter? 如何使 spring controller json 响应等到 firebase 查询结束? - How to make spring controller json response wait until firebase query ends? 等待firebase加载直到显示View - Wait for firebase to load until showing View 如何使依赖于先前功能数据的 function 等到设置该数据 - How to make a function which relies on a previous functions data wait until that data is set Airflow `BeamRunPythonPipelineOperator` 确实尊重 `wait_until_finished = False` - Airflow `BeamRunPythonPipelineOperator` does respect `wait_until_finished = False` 在 Angular 和 rxjs 中获取 FireStorage URL 直到渲染 - get FireStorage URL in Angular with rxjs until rendering Terraform 等到执行 user_data 然后制作图像以自动缩放? - Terraform wait until execution of user_data then make an image to autoscale?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM