import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class GetImage { private static String PATH = "http://192.168.1.119:8080/ok/point_one.png"; public static void main(String[] args) { // TODO Auto-generated method stub savaDisk(); } //存到本地 public static void savaDisk(){ InputStream in = getInputStream(); FileOutputStream fos = null; byte[] data = new byte[1024]; int len = 0; try { fos = new FileOutputStream("D:\\test.png"); while((len = in.read(data))!=-1){ fos.write(data, 0, len); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(in!=null){ try { in.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(fos!=null){ try { fos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public static InputStream getInputStream() { InputStream in = null; HttpURLConnection httpconn = null; try { // 声明url URL url = new URL(PATH); if (url != null) { // 建立客户端与服务器端链接 httpconn = (HttpURLConnection) url.openConnection(); // 设置网路超时时间,如果超过这个时间自动断开 httpconn.setConnectTimeout(3000); // 打开输入流 httpconn.setDoInput(true); // 设置请求方式 httpconn.setRequestMethod("GET"); // 获取响应的状态码 int responseCode = httpconn.getResponseCode(); // 判断是否是ok if (responseCode == 200) { // 从服务器获得一个输入流 in = httpconn.getInputStream(); } } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return in; } }
原文:http://www.cnblogs.com/84126858jmz/p/4906751.html