Article Directory
Recently, there was a need to download pictures from network resources, so Pidianpidian began to type codes, and finally encountered some. . . Forehead. . . A bit of a 'tricky' (had to complain about) problem.
A brief introduction to HttpURLConnection
The Java HttpURLConnection class is http specific URLConnection. It works for HTTP protocol only.
By the help of HttpURLConnection class, you can retrieve information of any HTTP URL such as header information, status code, response code etc.
- Only supports http protocol
- Information such as request headers and status codes can be obtained through HttpURLConnection
For a more detailed introduction, you can read the article written by this big guy- Detailed explanation and summary of the use of HttpURLConnection in java. Use of HttpClient
Real knowledge comes from practice
download images from the web
public static InputStream readImage(String encodeUrl) {
try {
URL url = new URL(encodeUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// conn.connect();
// 防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
conn.setRequestProperty("Accept-Encoding", "identity");
// 获取文件转化为byte流
InputStream inputStream = conn.getInputStream();
return inputStream ;
} catch (Exception e) {
log.info("下载网络图片url:{}失败!错误信息:{}", url, e.getMessage());
e.printStackTrace();
return null;
}
}
Encounter problems
The url carries Chinese, and the download fails
Transcode the Chinese part of the url
URLEncoder.encode(url, "utf-8");
The url contains spaces, and the download fails
This problem can be regarded as a pit between background transcoding and browser transcoding=_=||
URLEncoder spaces will be encoded +, while spaces in URI are %20
String encodeUrl = URLEncoder.encode(url, "utf-8");
encodeUrl = encodeUrl.replaceAll("\\+", "%20");
References
Detailed explanation and summary of the use of HttpURLConnection in Java HttpURLConnection class
java. Use of HttpClient