2017-12-08 42 views
1

Retrofit 2로 파일을 업로드하려고하는데 시간 제한을 추가 한 후에도 항상 "소켓 시간 초과 연결"오류가 발생합니다.retrofit2 okhttp3 android multipart socket tomeout 오류

내 나머지 클라이언트 설치 - -이 해결 방법에 대한 어떤 제안 SO에 대한 몇 가지 답변을 읽은 후

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); 
     } 
    } 

는 또한 시도 -

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 블록에 "소켓 시간 초과 오류 예외"를 얻고있다. 이제는 소켓 시간 초과 예외를 발생시키는 완전히 다른 오류 일 수 있습니다. 실제로는 시간 초과로 인해 발생합니다. 어느 쪽이든, 이것을 디버깅하거나 수정하는 방법에 대한 제안 사항이 있습니까?

+0

첫째, 좋은 stackoverflow 질문에 대해서는 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(); 
과 같은 가정하에하고

해피 코딩 :)