We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
联网是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的拦截器好像挺有意思的,等有时间也研究一下。
The text was updated successfully, but these errors were encountered:
把代码放在
```java 和 ```
之间
Sorry, something went wrong.
用markdown进行排版较之前好看了,另外也加上之前漏了的地方
Volley 也挺好用~
Volley
No branches or pull requests
联网是app的一个十分重要的功能。如今除了单机小游戏外,大部分app都依靠联网与后端联系。Okhttp是近几年android端一个非常火的联网框架(嗯!有框架就不要玩别的。),正好最近有上传文件的需求,就研究一下okhttp 怎样上传文件的。
啥都不说,直接上代码:
嗯,注释都有了,应该不用多说什么了。顺便说一句,在网上看到用原生的httpUrlConnection 实现上传时,需要用到输入输出流,较okhttp麻烦。
上传实现了,顺带也扯一下怎么加上带进度监听、参数上传。
要加进度的话,google搜到的是通过接口回调机制返回进度数据,然后在RequestBody()中复写如下函数。
The text was updated successfully, but these errors were encountered: