[英]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.这与您的方法之间存在一些关键差异。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.