下载方法本地无误,服务器部署报错:java.io.IOException: Server returned HTTP response code: 400 for URL:处理

问题描述:

通过图片url下载图片,本地运行正常使用,部署到服务器后开始报错,报错代码400

方法代码:

 /**
     * 通过图片url下载图片到指定文件夹
     * @param downloadUrl	图片url
     */
    public void downloadFile(String downloadUrl,String fileName) {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            //获取连接
            downloadUrl = URLEncoder.encode(downloadUrl, "UTF-8");
            downloadUrl= URLDecoder.decode(downloadUrl, "UTF-8");

            URL url=new URL(downloadUrl);
            HttpURLConnection connection=(HttpURLConnection)url.openConnection();
            connection.setConnectTimeout(3*1000);

            //设置请求头
            connection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36");
            connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");

            //获取输入流 
            inputStream=connection.getInputStream();
            
            File fileDir=new File(downloadDir);
            if(!fileDir.exists()){//如果文件夹不存在
                fileDir.mkdir();//创建文件夹
            }

            //截取文件名称,可以把 / 换成需要的规则
            String filePath = downloadDir+"/" + downloadUrl.substring(downloadUrl.lastIndexOf("/"));
            File file = new File(filePath);
            file.renameTo(new File(fileName));
            file.createNewFile();//创建文件,存在覆盖

            outputStream = new FileOutputStream(file);
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = inputStream.read(buf, 0, 1024)) != -1) {
                outputStream.write(buf, 0, len);
            }
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("文件下载出错:" + e);
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                logger.error("关闭流出错:" + e);
            }
        }
    }

报错信息:

java.io.IOException: Server returned HTTP response code: 400 for URL: https://file.sfaq.com.cn/insurance/货物运输企业安全_CN2023041718230168_1681786990862.docx
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
        at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
        at org.jeecg.modules.util.FileDownloadUtil.downloadFile(FileDownloadUtil.java:94)

报错代码行:

            //获取输入流 
            inputStream=connection.getInputStream();

处理方法:

一开始查到的都说是url链接的问题,使用encode方法,代码中已经重新解码过,说明不是此问题,从stackoverflow上查到的方法:
源地址:stackoverflow回答地址

报错行修改后可正常下载使用,修改内容为:

            //获取输入流 服务器上报错400,需判断获取数据流
            //inputStream=connection.getInputStream();
            if (connection.getResponseCode() >= 400) {
                inputStream = connection.getErrorStream();
            } else {
                inputStream = connection.getInputStream();
            }

试了好几种方法,使用此发方法解决了问题,避免以后忘记,记录一下,如果有更好的方法,欢迎补充指正~

2023-04-19 更新

找到错误原因了!!!!!居然是因为url链接中含有中文字符,单个文件下载的时候不会出错,但是多个文件通过链接从服务器下载然后压缩成zip文件的时候会报错,于是把所有上传的方法使用了pinyin4j包下的convertChineseToPinyin方法将中文转换成了拼音,之后就可以正常使用了~

<!--汉字转拼音-->
        <dependency>
            <groupId>com.belerweb</groupId>
            <artifactId>pinyin4j</artifactId>
            <version>2.5.0</version>
        </dependency>
String orgName = file.getOriginalFilename();
orgName = CommonUtils.convertChineseToPinyin(orgName,true, HanyuPinyinCaseType.LOWERCASE);

猜你喜欢

转载自blog.csdn.net/weixin_44934104/article/details/130217816