用HttpURLConnection 下载文件工具类


封装的工具类

package cn.com.bjhj.utils;

import android.os.Environment;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 文件下载utils
 * Created by JIANG on 2016/10/19.
 */
public class HttpClientUtils {
    private static final java.lang.String TAG ="HttpClientUtils" ;
    private String urlPath ;
    private String outPath;
    private String fileName;

    /**
     *
     * @param urlPath
     * @param outPath
     * @param fileName
     */
    public HttpClientUtils(String urlPath, String outPath, String fileName) {
        this.fileName = fileName;
        this.outPath = outPath;
        this.urlPath = urlPath;
    }

    /**
     * 下载文件
     */
    public void downloadFile()
    {
        // 启动新线程下载软件
        new downloadFileThread().start();
    }
    /**
     * 下载文件线程
     */
    private class downloadFileThread extends Thread {
        @Override
        public void run() {
            try {
                // 判断SD卡是否存在,并且是否具有读写权限
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    // 获得存储卡的路径
                    //http://182.92.158.132/cloud/cloudfile?path=/public/notice/201606101737302282/16-131109141345 (1)_20160610173730880.jpg
                    //http://182.92.158.132/cloud/cloudfile?path=/public/notice/201606101737302282/16-131109141345%20(1)_20160610173730880.jpg
                    L.d(TAG,"我是路径-===="+urlPath);
                    URL url = new URL(urlPath);
                    // 创建连接
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.connect();
                    L.i("头:"+conn.getHeaderFields());;
                    // 获取文件大小
                    int length = conn.getContentLength();
                    L.i("length .." + length);
                    // 创建输入流
                    InputStream is = conn.getInputStream();

                    File file = new File(outPath);
                    // 判断文件目录是否存在
                    if (!file.exists()) {
                        file.mkdirs();
                    }
                    File apkFile = new File(outPath,fileName);
                    FileOutputStream fos = new FileOutputStream(apkFile);
                    int count = 0;
                    // 缓存
                    byte buf[] = new byte[1024];
                    // 写入到文件中

                        int numread = is.read(buf);
                        count += numread;
                        L.i("count .."+ count +"  numread .." + numread);
                        // 写入文件
                        fos.write(buf, 0, numread);
                    fos.close();
                    is.close();
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }



        }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是一个Java本地测试文件上传的工具类示例: ```java import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class FileUploader { private static final String LINE_FEED = "\r\n"; private final String boundary; private HttpURLConnection httpConn; private final String charset; public FileUploader(String requestURL, String charset) throws IOException { this.charset = charset; // creates a unique boundary based on time stamp boundary = "===" + System.currentTimeMillis() + "==="; URL url = new URL(requestURL); httpConn = (HttpURLConnection) url.openConnection(); httpConn.setUseCaches(false); httpConn.setDoOutput(true); // indicates that we want to write to the HTTP request body httpConn.setDoInput(true); httpConn.setRequestMethod("POST"); httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); } public void addFilePart(String fieldName, File uploadFile) throws IOException { String fileName = uploadFile.getName(); httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); StringBuilder sb = new StringBuilder(); sb.append("--").append(boundary).append(LINE_FEED); sb.append("Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName + "\"" + LINE_FEED); sb.append("Content-Type: " + "application/octet-stream" + LINE_FEED); sb.append(LINE_FEED); byte[] headerBytes = sb.toString().getBytes(charset); byte[] trailerBytes = (LINE_FEED + "--" + boundary + "--" + LINE_FEED).getBytes(charset); httpConn.setRequestProperty("Content-Length", String.valueOf(headerBytes.length + uploadFile.length() + trailerBytes.length)); httpConn.getOutputStream().write(headerBytes); try (InputStream inputStream = uploadFile.toURI().toURL().openStream()) { byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { httpConn.getOutputStream().write(buffer, 0, bytesRead); } httpConn.getOutputStream().write(trailerBytes); } } public int finish() throws IOException { int status = httpConn.getResponseCode(); httpConn.disconnect(); return status; } } ``` 使用示例: ```java public static void main(String[] args) throws IOException { String charset = "UTF-8"; String requestURL = "http://localhost:8080/upload"; FileUploader fileUploader = new FileUploader(requestURL, charset); File uploadFile = new File("path/to/local/file"); fileUploader.addFilePart("file", uploadFile); int status = fileUploader.finish(); System.out.println("Server response code: " + status); } ``` 其中,`requestURL`是文件上传接口的URL,`uploadFile`是要上传的本地文件。你需要将它们替换为你自己的URL和文件路径。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值