The download method is correct locally, but the server deployment error: java.io.IOException: Server returned HTTP response code: 400 for URL: processing

Problem Description:

Download the picture through the picture url, and the local operation is normal. After deploying to the server, an error is reported, and the error code 400 is reported.

Method code:

 /**
     * 通过图片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);
            }
        }
    }

Error message:

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)

Error code line:

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

Approach:

What I found at the beginning was a problem with the url link. Using the encode method, the code has been re-decoded, indicating that this is not the problem. The method found on stackoverflow: source address: stackoverflow
answer address

After the error line is modified, it can be downloaded and used normally. The modified content is:

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

Tried several methods, using this method to solve the problem, to avoid forgetting in the future, record it, if there is a better method, welcome to add and correct~

Updated 2023-04-19

Found the cause of the error! ! ! ! ! It is because the url link contains Chinese characters, there will be no error when downloading a single file, but an error will be reported when multiple files are downloaded from the server through the link and then compressed into a zip file, so all upload methods are used under the pinyin4j package The convertChineseToPinyin method converts Chinese into pinyin, and then it can be used normally~

<!--汉字转拼音-->
        <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);

Guess you like

Origin blog.csdn.net/weixin_44934104/article/details/130217816