Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

使用okhttp上传文件 #62

Open
ibacor opened this issue Mar 26, 2017 · 3 comments
Open

使用okhttp上传文件 #62

ibacor opened this issue Mar 26, 2017 · 3 comments

Comments

@ibacor
Copy link

ibacor commented Mar 26, 2017

联网是app的一个十分重要的功能。如今除了单机小游戏外,大部分app都依靠联网与后端联系。Okhttp是近几年android端一个非常火的联网框架(嗯!有框架就不要玩别的。),正好最近有上传文件的需求,就研究一下okhttp 怎样上传文件的。

啥都不说,直接上代码:

    String URL,filePath;
    OkHttpClient mOkHttpClient;
    //创建File
    File file = new File(filePath);
    //创建RequestBody
    RequestBody body = RequestBody.create(MEDIA_OBJECT_STREAM, file);
    //创建Request
    Request request = new Request.Builder().url(requestUrl).post(body).build();
    Call call = mOkHttpClient.newBuilder().writeTimeout(50, 
    TimeUnit.SECONDS).build().newCall(request);
    call.enqueue(new Callback() {

    @Override
    public void onFailure(Call call, IOException e) {
    //上传失败
    }
    
    @Override
    public void onResponse(Call call, Response response) throws IOException {
    if (response.isSuccessful()) {
    //上传成功
    } else {
    //上传失败
    }
    }
    });

嗯,注释都有了,应该不用多说什么了。顺便说一句,在网上看到用原生的httpUrlConnection 实现上传时,需要用到输入输出流,较okhttp麻烦。
上传实现了,顺带也扯一下怎么加上带进度监听、参数上传。
要加进度的话,google搜到的是通过接口回调机制返回进度数据,然后在RequestBody()中复写如下函数。

	public <T> RequestBody createProgressRequestBody(final MediaType contentType, final File file, final ReqProgressCallBack<T> callBack) {
        return new RequestBody() {
            @Override
            public MediaType contentType() {
                return contentType;
            }

            @Override
            public long contentLength() {
                return file.length();
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                Source source;
                //这里也是要用到输入输出流
                try {
                    source = Okio.source(file);
                    Buffer buf = new Buffer();
                    long remaining = contentLength();
                    long current = 0;
                    for (long readCount; (readCount = source.read(buf, 2048)) != -1; ) {
                        sink.write(buf, readCount);
                        current += readCount;
                        //回调进度监听
                        progressCallBack(remaining, current, callBack);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
    }
额,好像忘了带参数,其实只要builder.addFormDataPart(arg0, arg1);用就好。
PS.之前看到okhttp的拦截器好像挺有意思的,等有时间也研究一下。
@SunDoge
Copy link

SunDoge commented Mar 26, 2017

把代码放在

```java

```

之间

@ibacor ibacor closed this as completed Mar 26, 2017
@ibacor ibacor reopened this Mar 26, 2017
@ibacor
Copy link
Author

ibacor commented Mar 26, 2017

用markdown进行排版较之前好看了,另外也加上之前漏了的地方

@Triple-Z
Copy link

Volley 也挺好用~

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants