相关代码
package com.mqp.clent; import java.io.BufferedOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; /** * 这个类的主要目的是从服务器端获取图片然后按照流的方式输出到那个盘符 1、通过GET方式从服务器端获取数据 2、通过POST方式向服务器端发送数据 * * @author Administrator * */ public class GetImage { // 服务器的地址 private final static String IMAGE_PATH = "http://192.168.0.108:8080/Http/sj.png"; static InputStream in = null; static HttpURLConnection httpUrl = null; static FileOutputStream fileOut = null; // 从服务器的到流文 public static InputStream getInputStream() { try { URL url = new URL(IMAGE_PATH); if (url != null) { httpUrl = (HttpURLConnection) url.openConnection();// 建立连接 httpUrl.setConnectTimeout(10000);// 设置超时时间 httpUrl.setRequestMethod("GET"); httpUrl.setDoInput(true);// 设置输入方式 int code = httpUrl.getResponseCode();// 得到服务器方返回的类型 if (code == 200) { in = httpUrl.getInputStream(); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (in != null) { try { in.close();// 关闭流 } catch (IOException e) { e.printStackTrace(); } } } return in; } // 将流文件输出出来 public static void writeFileToDark() { InputStream input = getInputStream(); BufferedOutputStream bos = null; // 指定输出的路径 try { // test.png指的是输出的名字 fileOut = new FileOutputStream("d://test//test.png"); bos = new BufferedOutputStream(fileOut); } catch (FileNotFoundException e1) { e1.printStackTrace(); } byte data[] = new byte[1024];// 每次循环输出多少个字节 int flag = 0; try { while ((flag = input.read(data)) != -1) {// 不等于-1就代表继续往下读 bos.write(data, 0, flag);// 输出到指定的路径 } } catch (IOException e) { e.printStackTrace(); } finally { try { fileOut.close();// 写完后关闭流 } catch (IOException e) { e.printStackTrace(); } } } public static void main(String[] args) { writeFileToDark(); } }