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 错误。