I am trying to upload a file with Retrofit 2 and it is giving me "socket timed connection out" error every time even after adding the timeout limits. Any suggestions on how to fix this -
My Rest client setup -
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);
}
}
After reading several answers on SO, I also tried -
OkHttpClient httpClient = new OkHttpClient.Builder()
.connectTimeout(12, TimeUnit.MINUTES)
.readTimeout(12, TimeUnit.MINUTES)
.writeTimeout(12, TimeUnit.MINUTES).build();
But, got the same timeout error with this also. File upload starting intent -
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);
on intent activity result -
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);
}
Now, I am getting "socket timeout error exception" in the onFailure block. Now, this might be an entirely different error which is throwing socket timeout exception or this is actually because of timeout. Either way, any suggestions as to how to debug or fix this ?
答案 0 :(得分: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();
快乐编码:)