在我们的应用中,有的时候会试探一个文件是否存在,一个图片是否存在,但是不去真正的去下载,特别是文件比较大的时候。那么这个时候,我们的代码应该如何写呢?下面是基于JDK 自身API的一种实现方式:使用HTTP的HEAD方法。
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.junit.Test;
public class URLTest {
@Test
public void testURL(){
String urlstr="https://www.broward.org/EasyPay/Learning/Documents/TimecardsSchedulesSupervUseGuide.pdf";
try {
long begin=System.currentTimeMillis();
URL url=new URL(urlstr);
HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("HEAD");
int responsecode=httpURLConnection.getResponseCode();
System.out.println("-----"+responsecode);
long end=System.currentTimeMillis();
System.out.println("--Time Consumed---"+(end-begin));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
如果Fiddler 4模拟,其报文如下: