【问题标题】:retrofit2 okhttp3 android multipart socket tomeout errorretrofit2 okhttp3 android multipart socket tomeout 错误
【发布时间】:2018-05-22 21:16:30
【问题描述】:

我正在尝试使用 Retrofit 2 上传文件,它给了我 即使在添加超时限制后,每次都会出现“套接字超时连接”错误。有关如何解决此问题的任何建议 -

我的 Rest 客户端设置 -

private static void setupRestClient() {
        if(LoginToken != null && !LoginToken.isEmpty()) {
            OkHttpClient httpClient = new OkHttpClient();
            httpClient.interceptors().add(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request request = chain.request().newBuilder().addHeader("Authorization", "Bearer "+ LoginToken).build();
                    return chain.proceed(request);
                }
            });
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(httpClient)
                    .build();
            REST_CLIENT = retrofit.create(Api.class);
        } else {
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
            REST_CLIENT = retrofit.create(Api.class);
        }
    }

在阅读了关于 SO 的几个答案后,我也尝试了 -

OkHttpClient httpClient = new OkHttpClient.Builder()
                    .connectTimeout(12, TimeUnit.MINUTES)
                    .readTimeout(12, TimeUnit.MINUTES)
                    .writeTimeout(12, TimeUnit.MINUTES).build();

但是,这个也有同样的超时错误。 文件上传开始意图 -

Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if(takePictureIntent.resolveActivity(EduwiserMainActivity.this.getPackageManager()) != null){
            File photoFile = null;
            try{
                photoFile = createImageFile();
                takePictureIntent.putExtra("PhotoPath", mCM);
            } catch(IOException ex){
                Log.e("Error:", "Image file creation failed", ex);
            }
            if(photoFile != null){
                dfCM = "file:" + photoFile.getAbsolutePath();
                mCM = photoFile.getPath();
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
            } else {
                takePictureIntent = null;
            }
        }
        Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
        contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
        contentSelectionIntent.setType("image/*");
        Intent[] intentArray;
        if(takePictureIntent != null){
            intentArray = new Intent[]{takePictureIntent};
        } else {
            intentArray = new Intent[0];
        }

        Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
        chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
        chooserIntent.putExtra(Intent.EXTRA_TITLE, "Choose image");
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
        startActivityForResult(chooserIntent, FCR);

关于意图活动结果 -

if(requestCode == FCR && resultCode == -1){
            try {
                File file = null;
                String[] proj = { MediaStore.Images.Media.DATA };
                String localPath = mCM != null && !mCM.isEmpty() ? mCM.replace("file:", "") : null;
                if(data == null || data.getData() == null){
                    //Capture Photo if no image available
                    if(localPath != null){
                        file = new File(localPath);
                    }
                } else {
                    String dataString = data.getDataString();
                    if(dataString != null){
                        try {
                            file = new File(PathUtil.getPath(this, Uri.parse(dataString)));
                        } catch (Exception e){
                            Log.e("error", e.toString());
                        }
                    }
                }
                final File newFile = file;
                defaultPd = new ProgressDialog(EduwiserMainActivity.this);
                if(token != null && !token.isEmpty() && newFile != null && documentUploadFileType != null && !documentUploadFileType.isEmpty()){
                    try {
                        if(defaultPd != null && !defaultPd.isShowing()) {
                            defaultPd.show();
                            defaultPd.setMessage("Uploading file...");
                        }
                        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), newFile);
                        MultipartBody.Part body = MultipartBody.Part.createFormData(!Objects.equals(documentUploadFileType, "profile") ? documentUploadFileType + "_file":
                                documentUploadFileType, documentUploadFileType + ".jpg", requestFile);
                        documentUploadFileType = null;
                        Call<LocalAuthResponse> call = RestClient.get(getApplicationContext()).uploadTeacherDocuments("Bearer " + token, body);
                        call.enqueue(new Callback<LocalAuthResponse>() {
                            @Override
                            public void onResponse(Call<LocalAuthResponse> call, Response<LocalAuthResponse> response) {
                                try {
                                    if(defaultPd != null && defaultPd.isShowing()) {
                                        defaultPd.dismiss();
                                    }
                                } catch (Exception e){}
                                try {
                                    if(response.body() != null && response.body().getSuccess()) {
                                        mWebView.evaluateJavascript("var event = new CustomEvent('refresh_userdata');document.dispatchEvent(event);", null);
                                    }
                                } catch (Exception e){
//                                mWebView.evaluateJavascript("var event = new CustomEvent('refresh_userdata');document.dispatchEvent(event);", null);
                                }
                            }

                            @Override
                            public void onFailure(Call<LocalAuthResponse> call, Throwable t) {
                                Toast.makeText(getApplicationContext(), "Error Uploading Documents. Please try again.", Toast.LENGTH_LONG).show();
                                try {
                                    if(defaultPd != null && defaultPd.isShowing()) {
                                        defaultPd.dismiss();
                                    }
                                } catch (Exception e){}
                                mWebView.evaluateJavascript("var event = new CustomEvent('fail_attachment');document.dispatchEvent(event);", null);
                            }
                        });
                    } catch (Exception e){
                        Log.e("error", e.toString());
                    }
                }
            } catch(Exception e){
                Log.e("error", e.toString());
            }
        } else if(requestCode == FCR){
            mWebView.evaluateJavascript("var event = new CustomEvent('fail_attachment');document.dispatchEvent(event);", null);
        }

现在,我在 onFailure 块中收到“套接字超时错误异常”。 现在,这可能是一个完全不同的错误,它引发了套接字超时异常,或者这实际上是因为超时。 无论哪种方式,有关如何调试或修复此问题的任何建议?

【问题讨论】:

  • 首先,对于好的stackoverflow问题,请包含stacktrace,以便清楚它在什么时候失败。
  • 我也会尝试,在您的 IDE 中而不是在移动设备上运行相同的请求,看看它是否与设备/网络相关。并尝试来自您的手机的一些类似请求,这些请求也不涉及文件上传。例如获取“/robots.txt”

标签: android sockets timeout retrofit2 okhttp3


【解决方案1】:

我假设您正在获取有效的图像文件,所以让我们来上传部分

@Multipart
@POST("api/image/upload")
Call<String> imageUpload(@Part MultipartBody.Part image, @Part("name") RequestBody name);

以及上传功能

    private void uploadImage(File file) {
    try {
        if (file.exists()) {
            RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
            MultipartBody.Part body = MultipartBody.Part.createFormData("upload", file.getName(), reqFile);
            RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "upload_test");
            RestClient.getService().imageUpload(body, name).enqueue(new Callback<String>() {
                @Override
                public void onResponse(@NonNull Call<String> call, @NonNull final Response<String> response) {
                    newImageUrl = response.body();
                }

                @Override
                public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {

                }
            });
        }
    } catch (Exception e) {
        toast("Please try again");
    }
}

我的改装看起来像这样

new Retrofit.Builder().baseUrl(ConfigHelper.DataServiceUrl)
                .addConverterFactory(converterFactory)
                .client(client
                        .addInterceptor(new Interceptor() {
                            public Response intercept(@NonNull Chain chain) throws IOException {
                                return chain.proceed(chain.request().newBuilder().addHeader("access_key", finalToken).build());
                            }
                        })
                        .addInterceptor(logging)
                        .build()).build();

快乐编码:)

【讨论】:

    猜你喜欢
    • 2017-09-05
    • 2017-10-28
    • 2017-06-05
    • 1970-01-01
    • 2017-08-24
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多