判断http链接中文件是否存在

        最近项目遇到需要从http请求下载文件到服务器,下载前需要判断下http中的文件是否存在。如果判断本地服务器上文件是否存在,用file.exists来判断。但是这个方法却无法判断http中文件是否存在。

        如果要判断http文件是否存在,用如下代码:

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
 
public class Main {
    public static void main(String[] args) {
        String urlString = "http://example.com/file.txt";
        try {
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("HEAD");
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                System.out.println("文件存在");
            } else {
                System.out.println("文件不存在");
            }
        } catch (IOException e) {
            System.out.println("连接失败");
        }
    }
}

如果对方系统需要身份验证,那么需要加如下代码。我们系统是需要token验证。加权限验证的代码如下:

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
 
public class Main {
    public static void main(String[] args) {
        String urlString = "http://example.com/file.txt";
        try {
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            
            //权限校验
            connection.setRequestProperty("X-JFrog-Art-Api","cmv125VmedaeDAFdafLFAF2ed");

            //HEAD请求,不返回响应体,但是有些服务器可能不支持,则改成GET请求
            connection.setRequestMethod("HEAD");
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                System.out.println("文件存在");
            } else {
                System.out.println("文件不存在");
            }
        } catch (IOException e) {
            System.out.println("连接失败");
        }
    }
}

判断http中文件是否存在可以利用java.nio的方法,代码如下:

import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
 
public class Main {
    public static void main(String[] args) {
        String urlString = "http://example.com/file.txt";
        try {
            URL url = new URL(urlString);
            Path path = Paths.get(url.toURI());
            if (Files.exists(path)) {
                System.out.println("文件存在");
            } else {
                System.out.println("文件不存在");
            }
        } catch (IOException e) {
            System.out.println("连接失败");
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一路奔跑1314

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值