HttpConnectUtil实现文件的上传下载

package rest.test;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;
import javax.activation.MimetypesFileTypeMap;
/**
 * 网络访问工具类
 * @author silk
 *
 */
public class HttpClientUtil {
    /**
     * get方法直接调用post方法
     * @param url 网络地址
     * @return 返回网络数据
     */
    public static String get(String url){
       //return post(url,null);
    	 HttpURLConnection conn=null;
         try {
             URL u = new URL(url);
             conn = (HttpURLConnection)u.openConnection();
             StringBuffer sb=null;
             //获取连接状态码
             int recode=conn.getResponseCode();
             BufferedReader reader=null;
             if(recode==200){
                 //Returns an input stream that reads from this open connection
                 //从连接中获取输入流
                 InputStream in=conn.getInputStream();
                 //对输入流进行封装
                 reader=new BufferedReader(new InputStreamReader(in,"UTF-8"));
                 String str=null;
                 sb=new StringBuffer();
                 //从输入流中读取数据
                 while((str=reader.readLine())!=null){
                     sb.append(str).append(System.getProperty("line.separator"));
                 }
                 //关闭输入流
                 reader.close();
                 if (sb.toString().length() == 0) {
                     return null;
                 }
                 return sb.toString().substring(0,
                         sb.toString().length() - System.getProperty("line.separator").length());
             }
         } catch (Exception e) {
             e.printStackTrace();
             return null;
         }finally{
             if(conn!=null)//关闭连接
                 conn.disconnect();
         }
         return null;
    }
    /**
     * 设定post方法获取网络资源,如果参数为null,实际上设定为get方法
     * @param url 网络地址
     * @param param 请求参数键值对
     * @return 返回读取数据
     */
   public static  String post(String url,Map<String,Object> param){
        HttpURLConnection conn=null;
        try {
            URL u=new URL(url);
            conn=(HttpURLConnection) u.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Charset", "utf-8");
			conn.setUseCaches(false);
			//默认为false,post方法需要写入参数,设定true
			//发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //设定post方法,默认get
            conn.setRequestMethod("POST");
			//conn.setConnectTimeout(10000);//连接超时 单位毫秒
            //conn.setReadTimeout(2000);//读取超时 单位毫秒
            StringBuffer sb=null;
            if(param!=null){//如果请求参数不为空
                sb=new StringBuffer();
                //获得输出流
                OutputStream out=conn.getOutputStream();
                //对输出流封装成高级输出流  注意编码格式,防止中文乱码
                BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(out,"UTF-8"));
                //将参数封装成键值对的形式  参数格式 xx=xx&yy=yy
                for(Map.Entry<String,Object> entry : param.entrySet()){
                    sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
                }
                //将参数通过输出流写入
                writer.write(sb.deleteCharAt(sb.toString().length()-1).toString());
                writer.flush();
                writer.close();//一定要关闭,不然可能出现参数不全的错误
                sb=null;
            }
            conn.connect();//建立连接
            sb=new StringBuffer();
            //获取连接状态码
            int recode=conn.getResponseCode();
            BufferedReader reader=null;
            if(recode==200){
                //从连接中获取输入流
                InputStream in=conn.getInputStream();
                //对输入流进行封装
                reader=new BufferedReader(new InputStreamReader(in,"UTF-8"));
                String str=null;
                sb=new StringBuffer();
                //从输入流中读取数据
                while((str=reader.readLine())!=null){
                    sb.append(str);
                }
                //关闭输入流
                in.close();
                in = null;
                reader.close();
                //关闭连接
                conn.disconnect();
                if (sb.toString().length() == 0) {
                    return null;
                }
                return sb.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }finally{
            if(conn!=null)//关闭连接
                conn.disconnect();
        }
        return null;
    }
   
   /** 
    * 上传图片 
    *  
    * @param urlStr 
    * @param textMap 
    * @param fileMap 
    * @return 
    */  
   public static String formUpload(String urlStr, Map<String, String> textMap,  
           Map<String, String> fileMap) {  
       String res = "";  
       HttpURLConnection conn = null;  
       String BOUNDARY = "-------------------"+UUID.randomUUID(); //boundary就是request头和上传文件内容的分隔符  
       try {  
           URL url = new URL(urlStr);  
           conn = (HttpURLConnection) url.openConnection();  
           conn.setConnectTimeout(5000);  
           conn.setReadTimeout(30000);  
           conn.setDoOutput(true);  
           conn.setDoInput(true);  
           conn.setUseCaches(false);  
           conn.setRequestMethod("POST");  
           conn.setRequestProperty("Connection", "Keep-Alive");  
           conn.setRequestProperty("User-Agent",  
                           "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");  
           conn.setRequestProperty("Content-Type",  
                   "multipart/form-data; boundary=" + BOUNDARY);  
 
           OutputStream out = new DataOutputStream(conn.getOutputStream());  
           // text  
           if (textMap != null) {  
               StringBuffer strBuf = new StringBuffer();  
               Iterator iter = textMap.entrySet().iterator();  
               while (iter.hasNext()) {  
                   Map.Entry entry = (Map.Entry) iter.next();  
                   String inputName = (String) entry.getKey();  
                   String inputValue = (String) entry.getValue();  
                   if (inputValue == null) {  
                       continue;  
                   }  
                   strBuf.append("\r\n").append("--").append(BOUNDARY).append(  
                           "\r\n");  
                   strBuf.append("Content-Disposition: form-data; name=\""  
                           + inputName + "\"\r\n\r\n");  
                   strBuf.append(inputValue);  
               }  
               out.write(strBuf.toString().getBytes());  
           }  
 
           // file  
           if (fileMap != null) {  
               Iterator iter = fileMap.entrySet().iterator();  
               while (iter.hasNext()) {  
                   Map.Entry entry = (Map.Entry) iter.next();  
                   String inputName = (String) entry.getKey();  
                   String inputValue = (String) entry.getValue();  
                   if (inputValue == null) {  
                       continue;  
                   }  
                   File file = new File(inputValue);  
                   String filename = file.getName();  
                   String contentType = new MimetypesFileTypeMap()  
                           .getContentType(file);  
                   if (filename.endsWith(".png")) {  
                       contentType = "image/png";  
                   }  
                   if (contentType == null || contentType.equals("")) {  
                       contentType = "application/octet-stream";  
                   }  
 
                   StringBuffer strBuf = new StringBuffer();  
                   strBuf.append("\r\n").append("--").append(BOUNDARY).append(  
                           "\r\n");  
                   strBuf.append("Content-Disposition: form-data; name=\""  
                           + inputName + "\"; filename=\"" + filename  
                           + "\"\r\n");  
                   strBuf.append("Content-Type:" + contentType + "\r\n\r\n");  
 
                   out.write(strBuf.toString().getBytes());  
 
                   DataInputStream in = new DataInputStream(  
                           new FileInputStream(file));  
                   int bytes = 0;  
                   byte[] bufferOut = new byte[1024];  
                   while ((bytes = in.read(bufferOut)) != -1) {  
                       out.write(bufferOut, 0, bytes);  
                   }  
                   in.close();  
               }  
           }  
 
           byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();  
           out.write(endData);  
           out.flush();  
           out.close();  
 
          
           StringBuffer strBuf = new StringBuffer();  
           BufferedReader reader = new BufferedReader(new InputStreamReader(  
                   conn.getInputStream()));  
           String line = null;  
           while ((line = reader.readLine()) != null) {  
               strBuf.append(line).append("\n");  
           }  
           res = strBuf.toString();  
           reader.close();  
           reader = null;  
       } catch (Exception e) {  
           e.printStackTrace();  
       } finally {  
           if (conn != null) {  
               conn.disconnect();  
               conn = null;  
           }  
       }  
       return res;  
   }  
   
   /**
    * 
    * @param urlPath
    *            下载路径
    * @param downloadDir
    *            下载存放目录
    * @return 返回下载文件
    */
   @SuppressWarnings("finally")
public static File downloadFile(String urlPath, String downloadDir) {
       File file = null;
       try {
           // 统一资源
           URL url = new URL(urlPath);
           URLConnection urlConnection = url.openConnection();
           HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
           // 设定请求的方法,默认是GET
           httpURLConnection.setRequestMethod("POST");
           // 设置字符编码
           httpURLConnection.setRequestProperty("Charset", "UTF-8");
           httpURLConnection.connect();
           // 文件大小
           int fileLength = httpURLConnection.getContentLength();
           // 文件名
           String filePathUrl = httpURLConnection.getURL().getFile();
           String fileFullName = filePathUrl.substring(filePathUrl.lastIndexOf(File.separatorChar) + 1);

           System.out.println("file length---->" + fileLength);

           BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());

           String path = downloadDir + File.separatorChar + fileFullName;
           file = new File(path);
           if (!file.getParentFile().exists()) {
               file.getParentFile().mkdirs();
           }
           OutputStream out = new FileOutputStream(file);
           int size = 0;
           int len = 0;
           byte[] buf = new byte[1024];
           while ((size = bin.read(buf)) != -1) {
               len += size;
               out.write(buf, 0, size);
               // 打印下载百分比
               // System.out.println("下载了-------> " + len * 100 / fileLength +
               // "%\n");
           }
           bin.close();
           out.close();
       } catch (MalformedURLException e) {
           e.printStackTrace();
       } catch (IOException e) {
           e.printStackTrace();
       } finally {
           return file;
       }

   }
  
   /**
    * 测试
    * @param args
    */
   public static void main(String[] args) {
	   //System.out.println(HttpClientUtil.get("http://www.baidu.com"));
	   downloadFile("http://img1.gtimg.com/news/pics/hv1/171/124/2203/143281866.jpg", "D:\\");
	   
   }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值