okhttpclient 文件断点上传

使用okhttpclient上传时,需要上传剩下一部分文件内容:


public class FileRequestBody extends RequestBody {

    private static final int SEGMENT_SIZE = 2048; // okio.Segment.SIZE

    private final InputStream inputStream;
    private final ProgressListener listener;
    private final String contentType;
    private long mBytesRead;

    public FileRequestBody (InputStream inputStream,String contentType,long lastCompletedBytes, ProgressListener listener) {
        this.inputStream = inputStream;
        this.contentType = contentType;
        this.listener = listener;
		this.mBytesRead = lastCompletedBytes;

    }

    @Override
    public long contentLength() {
 			try {
				return inputStream.available();
			}catch(Exception e){
				e.printStackTrace();
			}finally {
			}
			return 0;
    }

    @Override
    public MediaType contentType() {
        return MediaType.parse(contentType);
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        Source source = null;
        try {
            source = Okio.source(inputStream);
            long read;

			
            while ((read = source.read(sink.buffer(), SEGMENT_SIZE)) != -1) {
                mBytesRead += read;
                sink.flush();
                this.listener.transferred(total);

            }
        } finally {
            Util.closeQuietly(source);
        }
    }

    public interface ProgressListener {
        void transferred(long num);
    }

}

使用:
Builder HttpRequestBuild =  new Request.Builder();
HttpRequestBuild.url(fileUploadUrl);//自己上传url
File localFile = new File("xxx/xxx/xxx.txt");//自己上传的文件名字
RandomAccessFile file = new RandomAccessFile(localFile, "r");
file.seek(size);// 仅上传未完成的文件内容
RequestBody fileBody = FileRequestBody(file.getFD(),"application/octet-stream",
,size,
new FileRequestBody.ProgressListener(){  @Override void transferred(long num){};} ); 
 
HttpRequestBuild.put(fileBody);
//服务器中的标签
HttpRequestBuild.addHeader(
                "UploadFileRange",
                String.valueOf(size) + "-"
                        + localFile.length() - 1 + "/*");
 
Request  request = HttpRequestBuild.build();
Response response = mHttpClient.newCall(request).execute();
//注意关掉流
file.close();


 
  

部分代码引用以下网址:

http://stackoverflow.com/questions/25962595/tracking-progress-of-multipart-file-upload-using-okhttp





你可能感兴趣的:(android)