android - retrofit2 okhttp3 android multipart socket tomeout错误

标签 android sockets timeout retrofit2 okhttp3

我正在尝试使用Retrofit 2上传文件,这给了我
即使添加了超时限制,每次也会出现“socket定时连接超时”错误。对于如何解决这个问题,有任何的建议吗 -

我的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);

意图 Activity 结果-
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块中收到“套接字超时错误异常”。
现在,这可能是一个完全不同的错误,该错误引发套接字超时异常,或者这实际上是由于超时引起的。
无论哪种方式,关于如何调试或修复此问题的任何建议?

最佳答案

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

@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();

快乐编码:)

关于android - retrofit2 okhttp3 android multipart socket tomeout错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47717526/

相关文章:

在 CursorAdapter 中使用带有 ORMLite 的 Android 游标

java - 调用 notifyDataSetChanged 后 Android ListView 未更新

android - 让这个客户端服务器 android 应用程序工作。我在 edittext 窗口中输入什么 IP 地址?

javascript - 如果socketIO生成的ID是自动生成的,如何在两个用户之间建立通信?

java.io 和 socket.getInputStream()

android - 应用在什么情况下会删除Firebase Instance ID?

php - 使用 "php"命令运行的 PHP 脚本是否受超时限制影响?

c# - 使用 SQL 时 DBConnection 超时

java - 如何保持 jdbc 到 postgres 的存活

android - 应用程序上的用户数(未注销)是否等于 firebase 上的同时连接数?