首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Android Retrofit 2文件上传不起作用

Android Retrofit 2文件上传不起作用
EN

Stack Overflow用户
提问于 2016-11-14 20:14:37
回答 5查看 2.4K关注 0票数 2

我想开发一个应用程序,这是上传任何类型的文件到服务器。我拿到源代码了。但它只适用于图像。并且只上传小于2MB的图像文件。我想上传所有类型的文件。请帮帮我。我的代码如下所示。

MainActivity.java

代码语言:javascript
复制
public class MainActivity extends AppCompatActivity {
Service service;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button btn = (Button) findViewById(R.id.btn_upload);

    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

    // Change base URL to your upload server URL.
    service = new Retrofit.Builder().baseUrl("http://192.168.1.4/work/filesharing/").client(client).build().create(Service.class);

    if (btn != null) {
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String filePath1 = "/storage/emulated/0/gt.png";

                File file = new File(filePath1);

                RequestBody reqFile = RequestBody.create(MediaType.parse("*/*"), file);
                MultipartBody.Part body = MultipartBody.Part.createFormData("uploaded_file", file.getName(), reqFile);
                RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "upload_test");



                retrofit2.Call<okhttp3.ResponseBody> req = service.postImage(body, name);
                req.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        t.printStackTrace();

                        Log.d("failure", "message = " + t.getMessage());
                        Log.d("failure", "cause = " + t.getCause());
                    }
                });

            }
        });
    }
}

}

上传超过2MB的zip文件时将显示错误。

代码语言:javascript
复制
11-14 17:09:14.369 13895-13960/app3.acs.com.file_upload2 D/OpenGLRenderer: Enabling debug mode 0
11-14 17:09:16.068 13895-13993/app3.acs.com.file_upload2 D/OkHttp: --> POST http://192.168.1.4/work/filesharing/6.php HTTP/1.1
11-14 17:09:16.068 13895-13993/app3.acs.com.file_upload2 D/OkHttp: Content-Type: multipart/form-data; boundary=b2c1d03e-f7a5-4e3f-89e1-d1c20358f7dc
11-14 17:09:16.070 13895-13993/app3.acs.com.file_upload2 D/OkHttp: Content-Length: 20862337
11-14 17:09:16.934 13895-13919/app3.acs.com.file_upload2 W/art: Suspending all threads took: 30.363ms
11-14 17:09:16.935 13895-13993/app3.acs.com.file_upload2 I/art: Alloc partial concurrent mark sweep GC freed 20318(40MB) AllocSpace objects, 0(0B) LOS objects, 35% free, 28MB/44MB, paused 644us total 49.776ms
11-14 17:09:18.272 13895-13993/app3.acs.com.file_upload2 I/art: Alloc sticky concurrent mark sweep GC freed 8(256B) AllocSpace objects, 0(0B) LOS objects, 10% free, 68MB/76MB, paused 1.012ms total 6.892ms
11-14 17:09:18.293 13895-13993/app3.acs.com.file_upload2 I/art: Alloc partial concurrent mark sweep GC freed 6(192B) AllocSpace objects, 0(0B) LOS objects, 18% free, 68MB/84MB, paused 1.310ms total 18.796ms
11-14 17:09:18.330 13895-13993/app3.acs.com.file_upload2 I/art: Alloc concurrent mark sweep GC freed 6(12KB) AllocSpace objects, 0(0B) LOS objects, 18% free, 68MB/84MB, paused 627us total 34.490ms
11-14 17:09:18.332 13895-13993/app3.acs.com.file_upload2 I/art: Forcing collection of SoftReferences for 36MB allocation
11-14 17:09:18.371 13895-13993/app3.acs.com.file_upload2 I/art: Alloc concurrent mark sweep GC freed 11(344B) AllocSpace objects, 0(0B) LOS objects, 18% free, 68MB/84MB, paused 569us total 38.975ms
11-14 17:09:18.373 13895-13993/app3.acs.com.file_upload2 E/art: Throwing OutOfMemoryError "Failed to allocate a 38772598 byte allocation with 16777120 free bytes and 27MB until OOM"
11-14 17:09:18.381 13895-13993/app3.acs.com.file_upload2 E/AndroidRuntime: FATAL EXCEPTION: OkHttp Dispatcher
                                                                       Process: app3.acs.com.file_upload2, PID: 13895
                                                                       java.lang.OutOfMemoryError: Failed to allocate a 38772598 byte allocation with 16777120 free bytes and 27MB until OOM
                                                                           at java.lang.String.<init>(String.java:332)
                                                                           at java.lang.String.<init>(String.java:371)
                                                                           at okio.Buffer.readString(Buffer.java:579)
                                                                           at okio.Buffer.readString(Buffer.java:562)
                                                                           at okhttp3.logging.HttpLoggingInterceptor.intercept(HttpLoggingInterceptor.java:195)
                                                                           at okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java:187)
                                                                           at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:160)
                                                                           at okhttp3.RealCall.access$100(RealCall.java:30)
                                                                           at okhttp3.RealCall$AsyncCall.execute(RealCall.java:127)
                                                                           at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
                                                                           at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
                                                                           at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
                                                                           at java.lang.Thread.run(Thread.java:818)
11-14 17:09:20.069 13895-13993/app3.acs.com.file_upload2 I/Process: Sending signal. PID: 13895 SIG: 9
EN

回答 5

Stack Overflow用户

发布于 2018-07-01 01:06:54

我在上传大图片或视频时也遇到了同样的问题。主要的问题是你在HttpLoggingInterceptor中使用body level,而logger在logcat中打印你的文件,触发了一个java.lang.OutOfMemoryError异常。

如果您不想禁用body level loggin,可以添加此代码,以避免在打印大文件内容时使用loggin。我创建了自己的HttpLoggingInterceptor,并添加了一个if条件,以便在content-length > 10Ks的情况下跳过正文登录。

HttpLoggingInterceptor是最后一个类,所以你不能重写它。您可以复制一份HttpLoggingInterceptor文件并替换以下原始代码:

代码语言:javascript
复制
if (!logBody || !hasRequestBody) {
            logger.log("--> END " + request.method());
        } else if (bodyEncoded(request.headers())) {
            logger.log("--> END " + request.method() + " (encoded body omitted)");
        } else {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);
            //[...]

使用以下代码:

代码语言:javascript
复制
if (!logBody || !hasRequestBody) {
            logger.log("--> END " + request.method());
        } else if (bodyEncoded(request.headers())) {
            logger.log("--> END " + request.method() + " (encoded body omitted)");
        } else if (requestBody.contentLength()>1024 * 10) { //>10Kb
            logger.log("--> END " + request.method() + " (contentLength > 10Kb --> omitted)");
        } else {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);
            //[...]

我希望这对任何人都有帮助。对不起,我的英语;)。

票数 1
EN

Stack Overflow用户

发布于 2016-11-14 20:23:08

请降低日志记录级别或将其全部删除

查看此链接https://github.com/square/retrofit/issues/540上的JakeWharton回复

“通过调用.setLogLevel(RestAdapter.LogLevel.FULL),您强制Retrofit将整个请求正文缓冲到内存中,以便它可以记录日志。这就是在堆栈跟踪中调用readBodyToBytesIfNecessary所做的事情。

只应在调试时启用此类日志记录。“

票数 0
EN

Stack Overflow用户

发布于 2016-11-14 20:25:46

它与这个问题有关,https://github.com/square/retrofit/issues/540。你可以禁用你的拦截器Level.BODY。它可以在所有类型文件中工作,你有没有尝试过其他类型文件?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40588547

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档