package com.david.HttpURLConnectionDemo;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class Test02 {
/**
* HttpURLConnection
* 下载服务器上的一张图片到本地
* @param args
* 联系QQ:986945193
*
* 微博:http://weibo.com/mcxiaobing
*/
public static void main(String[] args) {
try {
URL url = new URL("http://10.2.163.69:8080/SZ1507Web/img/dog01.jpg");
HttpURLConnection conn = null;
try {
URLConnection urlCon = url.openConnection(); // 获取一个URLConnection
conn = (HttpURLConnection)urlCon;
conn.setConnectTimeout(5000);//设置连接超时时长
int code = conn.getResponseCode();//返回连接状态
if(code == 200){ //表示连接成功
System.out.println("连接成功...");
InputStream is = null;
OutputStream os = null;
try{
is = conn.getInputStream(); //获取 输入流
os = new FileOutputStream("dog1.jpg");
byte b[] = new byte[1024];
int num = 0;
while((num = is.read(b)) != -1){
os.write(b,0,num);
}
}catch(IOException e){
e.printStackTrace();
}finally{
is.close();
os.close();
}
}else{
System.out.println("网络连接异常");
}
} catch (IOException e) {
e.printStackTrace();
}finally{
conn.disconnect();//关闭
System.out.println("文件下载完成...");
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
程序员小冰博客:http://blog.csdn.net/qq_21376985
技术交流QQ986945193
微博:http://weibo.com/mcxiaobing