- /**
- * 获取HTTP网络资源
- * TCP通信编程适用于HTTP协议
- * 一边下载一边将字节保存在 ByteArrayOutputStream中
- * 最后通过toByteArray()一次性将字节数组写入文件
- * 适用于下载小文件,远程文件较大时,容易导致JVM溢出
- * 在目录下生成与远程文件同名的文件
- * 输入命令 http://127.0.0.1/Java/1.txt
- * */
- import java.net.URL;
- import java.net.HttpURLConnection;
- import java.io.BufferedInputStream;
- import java.io.FileOutputStream;
- import java.io.ByteArrayOutputStream;
- import java.io.IOException;
- public class TestHttpConnection {
- public static void main(String[] args) {
- try {
- HttpURLConnection httpConnection = (HttpURLConnection) new URL(
- args[0]).openConnection();
- httpConnection.setRequestMethod("GET");// 设置URL请求的方法
- BufferedInputStream bis = new BufferedInputStream(httpConnection
- .getInputStream());// 返回从打开的连接读取的字节输入流
- // 读入超过时间,会抛出SocketTimeoutException异常
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- byte[] buff = new byte[1024];
- int bytesRead;
- while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
- baos.write(buff, 0, bytesRead);
- }
- buff = null;
- String fileName = args[0].substring(args[0].lastIndexOf("/") + 1);
- FileOutputStream fos = new FileOutputStream(fileName);
- fos.write(baos.toByteArray());
- baos.close();
- fos.close();
- } catch (IOException ioe) {
- ioe.printStackTrace();
- }
- }
- }