Android改型2 JSON对象上载进度百分比
我使用改型2将JSON上传到服务器。JSON有一些BASE64编码的图像,因此上传整个图像需要时间。我想看看上传的百分比。我已经找到了现有文件的解决方案,但这不是一个文件,服务器只接受此表单。对于其他有相同问题的人,我已经从这个库中改编了一个帮助器类(ProgressOutputStream):我的工作代码如下:(用于上传文件,也用于上传json) ===========Android改型2 JSON对象上载进度百分比,android,json,upload,retrofit,progress,Android,Json,Upload,Retrofit,Progress,我使用改型2将JSON上传到服务器。JSON有一些BASE64编码的图像,因此上传整个图像需要时间。我想看看上传的百分比。我已经找到了现有文件的解决方案,但这不是一个文件,服务器只接受此表单。对于其他有相同问题的人,我已经从这个库中改编了一个帮助器类(ProgressOutputStream):我的工作代码如下:(用于上传文件,也用于上传json) =========== import java.io.IOException; import java.io.OutputStream; clas
import java.io.IOException;
import java.io.OutputStream;
class ProgressOutputStream extends OutputStream {
private final OutputStream stream;
private final UploadProgressRequestBody.ProgressListener listener;
private long total;
private long totalWritten;
ProgressOutputStream(OutputStream stream, UploadProgressRequestBody.ProgressListener listener, long total) {
this.stream = stream;
this.listener = listener;
this.total = total;
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
this.stream.write(b, off, len);
if (this.total < 0) {
this.listener.update(-1, -1);
return;
}
if (len < b.length) {
this.totalWritten += len;
} else {
this.totalWritten += b.length;
}
this.listener.update(this.totalWritten, this.total);
}
@Override
public void write(int b) throws IOException {
this.stream.write(b);
if (this.total < 0) {
this.listener.update(-1, -1);
return;
}
this.totalWritten++;
this.listener.update(this.totalWritten, this.total);
}
@Override
public void close() throws IOException {
if (this.stream != null) {
this.stream.close();
}
}
@Override
public void flush() throws IOException {
if (this.stream != null) {
this.stream.flush();
}
}
}
OkHttpClient client = new OkHttpClient.Builder()
.addNetworkInterceptor(new Interceptor() {
@Override public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
if (originalRequest.body() == null) {
return chain.proceed(originalRequest);
}
Request progressRequest = originalRequest.newBuilder()
.method(originalRequest.method(),
new UploadProgressRequestBody(originalRequest.body()))
.build();
return chain.proceed(progressRequest);
}
}).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
OkHttpClient client = new OkHttpClient.Builder()
.addNetworkInterceptor(new Interceptor() {
@Override public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
if (originalRequest.body() == null) {
return chain.proceed(originalRequest);
}
Request progressRequest = originalRequest.newBuilder()
.method(originalRequest.method(),
new UploadProgressRequestBody(originalRequest.body()))
.build();
return chain.proceed(progressRequest);
}
}).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();