zoukankan      html  css  js  c++  java
  • Android开发之下载服务器上的一张图片到本地java代码实现HttpURLConnection

    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
  • 相关阅读:
    ACdream 1224 Robbers (贪心)
    HDU 4320 Arcane Numbers 1 (质因子分解)
    在脚本中重定向输入
    呈现数据
    shell中的for、while、until(二)
    shell中的for、while、until
    C 指针疑虑
    结构化命令
    fdisk -c 0 350 1000 300命令
    PC机上的COM1口和COM2口
  • 原文地址:https://www.cnblogs.com/mcxiaobing/p/5472082.html
Copyright © 2011-2022 走看看