前提:已经搭建了一个本地服务器
-URL_PATH为服务器地址-
建立连接
url(aim) -> httpurlconnection(to get) ->inputstream(content)
public static InputStream getInputStream(){
InputStream inputStream=null;
URL url= null;
HttpURLConnection httpURLConnection=null;
try {
url = new URL(URL_PATH);
if(url!=null){
try {
httpURLConnection=(HttpURLConnection)url.openConnection();
httpURLConnection.setConnectTimeout(3000);
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestMethod("GET");
int responseCode=httpURLConnection.getResponseCode();
if(responseCode==200){
inputStream=httpURLConnection.getInputStream();
}
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
return inputStream;
}
下载到本地
Inputstream-> byte类型data数组[1024](中转站) -> fileoutstream(data,0,len) ->注意inputstream、fileoutputstream的关闭 finally
package com.http.get;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
// code
public class HttpUtils {
private static String URL_PATH = "http://192.168.2.210:8080/pro1.png";
HttpUtils() {
}
public static void saveImageToDisk() {
InputStream inputStream = getInputStream();
byte[] data = new byte[1024];
int len = 0;
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream("D:\\test.png");
while ((len = inputStream.read(data)) != -1) {
fileOutputStream.write(data, 0, len);
}
System.out.println("finish!");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (inputStream != null)
inputStream.close();
if (fileOutputStream != null)
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// the input stream
public static InputStream getInputStream() {
InputStream inputStream = null;
URL url = null;
HttpURLConnection httpURLConnection = null;
try {
url = new URL(URL_PATH);
if (url != null) {
try {
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(3000);
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestMethod("GET");
int responseCode = httpURLConnection.getResponseCode();
if (responseCode == 200) {
inputStream = httpURLConnection.getInputStream();
}
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
return inputStream;
}
public static void main(String[] args) {
saveImageToDisk();
}
}
工具: idea2019
相关链接:
创建web项目 https://cloud.tencent.com/developer/article/1425185
idea导入eclipse web项目 https://www.cnblogs.com/lindp/p/4484390.html