java下载网络文件+Illegal character in path at index 135错误解决方法

 public void downloadNetTest() throws URISyntaxException {
 		//图片的地址
        String netfileurl = "http://192.168.0.1:8080/files/10001005/图片(2020-06-02 09-21-31).jpg";
        //需要保存到的地址
        String baocunurl = "F:\\normalFiles\\222.jpg";
        int bytesum = 0;
        int byteread = 0;
        FileOutputStream fs = null;
        try {
            URL url = new URL(netfileurl);
            URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
            String urlStr = uri.toASCIIString();
            URL urll = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) urll.openConnection();
            // 设置超时间为5秒
            conn.setConnectTimeout(5 * 1000);
            conn.setRequestMethod("GET");
            InputStream inStream = conn.getInputStream();
            fs = new FileOutputStream(baocunurl);
            byte[] buffer = new byte[1204];
            while ((byteread = inStream.read(buffer)) != -1) {
                bytesum += byteread;
                fs.write(buffer, 0, byteread);
            }
        } catch (FileNotFoundException e) {
            logger.error(e.getMessage(),e);
        } catch (IOException e) {
            logger.error(e.getMessage(),e);
        }
        finally {
            try {
                fs.close();
            } catch (IOException e) {
                logger.error(e.getMessage(),e);
            }
        }
    }

netfileurl =http://192.168.0.1:8080/files/10001005/图片(2020-06-02 09-21-31).jpg
地址中存在空格,涉及了特殊字符,如‘|’‘&’等在这里插入图片描述
此处只能先把String转成URL,再通过URL生成URI的方法来解决问题,不能直接用String代替URI来访问,如果使用

URI uri=new URI(netfileurl);

创建URI对象,就会报Illegal character in path at index 错误。
此处尝试过使用

netfileurl = URLEncoder.encode(netfileurl, "UTF-8"); 
URI uri=new URI(netfileurl);

进行格式转换,不能解决Illegal character in path at index 错误。

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值