一、下载图片至本地示例代码
public class DownloadImage {
public static void main(String[] args) throws IOException {
// 下载到指定目录
File img = new File("D:\\tmp\\20100817072651150.jpg");
URL url = new URL("https://gerenziliao.os8.cn/hdos/UploadFiles/2010-08/admin/20100817072651150.jpg");
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
try (InputStream inputStream = urlConnection.getInputStream();
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
OutputStream out = new FileOutputStream(img);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(out)) {
byte[] buffer = new byte[1024];//每次读取/写入大小是1k
for (int len = 0; (len = bufferedInputStream.read(buffer)) > 0; ) {
bufferedOutputStream.write(buffer, 0, len);
// bufferedOutputStream关闭时会自动刷新,否则需显示调用该方法
// bufferedOutputStream.flush();
}
}
}
}
通过Java HTTP连接将网络图片下载到本地
httpClient4.2官方文档研究
JAVA压缩图片并打成ZIP
二、Java代理 GET 访问示例代码
/**
* 使用Java发送get 代理请求
*
* @param url url
* @return {@link String}
* @throws IOException IO异常
*/
protected String getWithJava(String url) throws IOException {
// 设置代理服务器的地址和端口
String proxyHost = "109.246.120.208";
int proxyPort = 1234;
// 创建代理对象
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
// 创建连接
URL address = restTemplate.getUriTemplateHandler().expand(url).toURL();
HttpURLConnection conn = (HttpURLConnection) address.openConnection(proxy);
// 设置请求方法和超时时间
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
// 头信息 USER_AGENT 设置好像不生效,待验证
conn.setRequestProperty(HttpHeaders.USER_AGENT, USER_AGENT[ThreadLocalRandom.current().nextInt(USER_AGENT.length)]);
// 读取数据
try (InputStream inputStream = conn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader in = new BufferedReader(inputStreamReader)) {
String inputLine;
StringBuilder response = new StringBuilder();
while (Objects.nonNull(inputLine = in.readLine())) {
response.append(inputLine);
}
return response.toString();
}
}