2017-12-08 12 views
1

Retrofit 2でファイルをアップロードしようとしていて、タイムアウトの制限を追加した後でも毎回 「ソケットタイムアウト接続」エラーが発生しています。この問題を解決する方法上の任意の提案 -retrofit2 okhttp3 android multipart socket tomeoutエラー

マイレストクライアントのセットアップ -

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

をしかし、と同じタイムアウトエラーを得た -

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上のいくつかの答えを読んだ後には、私も試してみましたこれもまた。意図開始 ファイルアップロード - 意思活動の結果に

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ブロックに "ソケットタイムアウトエラー例外" を取得しています。 これはソケットタイムアウト例外をスローしているまったく異なるエラーかもしれませんが、これは実際にはタイムアウトのためです。いずれにしても、これをデバッグまたは修正する方法に関する提案はありますか?

+0

まず、スタックオーバーフローの問題については、stacktraceを含めると、どの時点で失敗しているかが分かります。 –

+0

私はまた、モバイルではなくIDEで同じ要求を実行して、デバイス/ネットワークに関連するかどうかを確認しようとします。また、あなたのモバイルからファイルのアップロードを含まない同様のリクエストを試してみてください。例えばGET "/robots.txt" –

答えて

0

私はあなたがそうセクション

@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(); 
のように見えることができます有効なイメージファイルを取得していると仮定しています

ハッピーコーディング:)

関連する問題